我给时出错
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 继承自 User.ts,User.ts 包含以下代码:
export interface User {
firstName:string,
lastName:string,
age?:number,
address?:{
street?: string,
city?:string,
state?:string
}
}
添加?
到用户在其他文件中显示错误:
还有另一个名为 users 的文件夹......这是主要的......现在当我添加?在这里,它向我展示了这个错误。
这是由 TypeScript 的 Strict Class Initialization 引起的。
要解决此问题,您必须声明该类型可以同时为 Foo|undefined,或者使用 '!' 表示根据上述文档确定分配的符号:
情况1:
@Component({...})
export class Component {
@Input() myInput: string|undefined;
}
我们指出类型可以是字符串或未定义。
案例2:
@Component({...})
export class Component {
@Input() myInput!: string;
}
在这种情况下,我们使用 ! 符号表示我们知道它myInput
没有在构造函数中初始化,我们将在其他地方处理它。
如果您不关心严格的类初始化,您可以tsconfig.json
通过在编译器选项中添加一个标志来完全禁用该功能
{
"compilerOptions": {
"strictPropertyInitialization": false
}
}
注意:您必须重新启动 TypeScript 服务器才能重新应用 compilerOptions。实现此目的的最简单方法是简单地重新启动您的 IDE。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句