Angular属性修饰器在最新的VSCode中抛出"Property'x'没有初始化程序..."错误

Kyl*_* V. 9 typescript visual-studio-code angular

我将在这里引用Angular指南并使用此示例代码.

自从我上次更新我的Visual Studio代码以来,我已经开始在我的Angular组件.ts文件中使用Angular装饰器(例如)装饰的属性下的红色下划线@Input.在示例代码下面我会看到一个红色下划线下@Input() hero: Hero;@Input('master') masterName: string;:

import { Component, Input } from '@angular/core';

import { Hero } from './hero';

@Component({
  selector: 'app-hero-child',
  template: `
    <h3>{{hero.name}} says:</h3>
    <p>I, {{hero.name}}, am at your service, {{masterName}}.</p>
  `
})
export class HeroChildComponent {
  @Input() hero: Hero;
  @Input('master') masterName: string;
}
Run Code Online (Sandbox Code Playgroud)

以下是红色下划线的错误消息:

[ts]属性'masterName'没有初始值设定项,并且在构造函数中没有明确赋值.

我不知道为什么这些突然出现,我希望他们离开.我会喜欢做的事就是初始化一些一次性的价值,这可能是罚款,string但对类,比如Hero我绝对不希望有这样做.

提前致谢!

Deb*_*ahK 30

检查tsconfig.json文件并确保strictPropertyInitialization为false.

有关详细信息,请参阅本文档的"严格类初始化"部分:http://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html

注意:如果有的话

"strict": true,
Run Code Online (Sandbox Code Playgroud)

在您的tsconfig.json文件中设置,它现在将自动设置此新的严格属性,并使您看到所有这些通知.

所以你可以把它改成:

"strict": true,
"strictPropertyInitialization": false,
Run Code Online (Sandbox Code Playgroud)


Geo*_*rge 12

从TypeScript 2.7开始,答案是使用Definite Assignment Assertions

角度语法

export class HeroChildComponent {
    @Input('master') masterName!: string;
Run Code Online (Sandbox Code Playgroud)

AngularJS + TypeScript语法

export class HeroChildComponent {
    public masterName!: string;
Run Code Online (Sandbox Code Playgroud)

这允许将特定属性标记为"是的我宣布这将在这里,所以不要管它".这样,您可以选择在您知道为真的情况下退出,并且默认情况下检查初始化的默认行为仍然是打开的.

但是......在评论时2/26/2018 Webstorm和其他可能的IDE不接受它作为有效语法,所以解决它的唯一方法是关闭tsConfig中的"strictPropertyInitialization".

Webstorm 2018 EAP 181.3741表示它包含支持Definite Assignment Assertions所需的更新

这个线程来看,我认为最新的VSCode确实支持Definite Assignment Assertions