typescript 类型“Object”不能赋给类型“null”

xkrw2x1b  于 2023-01-27  发布在  TypeScript
关注(0)|答案(4)|浏览(608)

在我添加了一个名为ngInit的函数(该函数将调用服务类中的getCountries函数)之后,我得到了这个“类型”对象“不可分配给类型”null“"的错误。

import { Component, OnInit } from '@angular/core';
import {MessageService} from './message.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  title = 'Tour of Heroes';

  countryData = null;
  constructor(private api:MessageService) {}
  ngOnInit() {
    this.api.getCountries().subscribe((data)=>{
      this.countryData = data;
    });
  }

}
rseugnpd

rseugnpd1#

由于countryData = null属性的初始化,TypeScript推断countryData的类型为null。将null以外的任何值分配给此属性都将导致您看到的错误。
要修复,您可以:
1.键入any的属性:

countryData: any = null;

1.定义数据类型,并将属性设置为该类型或null

countryData: CountryDataType | null = null;

1.定义数据类型,将属性设置为该类型,并将其标记为可选(请注意,在本例中,初始值为undefined,而不是null):

countryData?: CountryDataType;
wkyowqbh

wkyowqbh2#

您已经在tsconfig中将返回类型声明为null或关闭strictNullChecks。
将类型null更改为any。

j0pj023g

j0pj023g3#

要使其正常工作,只需将类型更改为any或为国家/地区提供接口

countryData: any;

或者叫罗比

countryData:CountryDateType
ddhy6vgd

ddhy6vgd4#

当你用null初始化countryData时,编译器会将新值与null类型进行比较--这与你用String类型初始化它并尝试分配一个Number类型是一样的。如果你需要一次性的解决方案,只需使用类型转换。

this.countryData = data as any

而不是this.countryData = data
因此:如果你想让这个字段类型检查免疫只需看看@Vignesh答案.

相关问题