该属性没有初始化程序,并且在构造函数中未明确分配 [英] Property has no initializer and is not definitely assigned in the constructor

查看:436
本文介绍了该属性没有初始化程序,并且在构造函数中未明确分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我给我一个错误

export class UserComponent implements OnInit {
user:User;
constructor(){
    
    
}

ngOnInit(){  

    this.user = {
        firstName : "test",
        lastName : "test",
        age : 40,
        address: {
            street : "Test",
            city : "test",
            state: "test"
        }
    }
    
  }

}

我收到此错误:

Property 'user' has no initializer and is not definitely assigned in the constructor.

用户是从User.ts继承的,而User.ts包含以下代码:

user is inherited from User.ts and User.ts contains the below code:

export interface User {
firstName:string,
lastName:string,
age?:number,
address?:{
    street?: string,
    city?:string,
    state?:string
}


}

向用户添加?在其他文件中显示错误:

Adding ? to user is showing error in some other file:

还有一个名为用户的文件夹...这是主要文件夹...现在添加时?在这里,它向我显示此错误.

There is another folder named users...That is the main one...Now when I add ? here, it shows me this error.

推荐答案

这是由TypeScript的严格类初始化引起的.

This is caused by TypeScript's Strict Class Initialization.

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#strict-class-initialization

要解决此问题,您必须声明类型都可以为Foo | undefined,或使用'!'表示根据上述说明文件的明确分配的符号:

To resolve this issue you must either declare that the type can be both Foo|undefined, or utilize the '!' symbol to indicate definite assignment as per the above documentation:

情况1:

@Component({...})
export class Component {
  @Input() myInput: string|undefined;
}

我们指出类型可以是字符串,也可以是未定义的.

We indicate that the type may be either a string or undefined.

情况2:

@Component({...})
export class Component {
  @Input() myInput!: string;
}

在这种情况下,我们利用!表示我们知道 myInput 尚未在构造函数中初始化的符号,我们将在其他地方处理它.

In this case we utilize the ! symbol to indicate that we are aware that myInput is not initialized in the constructor and we will handle it elsewhere.

如果您不关心严格的类初始化,则可以通过在编译器选项中添加标志来完全禁用 tsconfig.json 中的功能

If you do not care about strict class initialization, you can disable the feature completely in your tsconfig.json by adding a flag to your compiler options

{
 "compilerOptions": {
    "strictPropertyInitialization": false
  }
}

注意:您将必须重新启动TypeScript服务器,才能重新应用compilerOptions.最简单的方法是重新启动IDE.

Note: You will have to restart the TypeScript server for the compilerOptions to be reapplied. The easiest way to achieve this is to simply restart your IDE.

这篇关于该属性没有初始化程序,并且在构造函数中未明确分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆