用于检查未定义和 NULL class 属性的 TSLint 规则

TSLint rules for checking undefined and NULL class properties

在我的 Web 应用程序中,当我定义必须包含某些数据类型的 class 属性 时,我总是指定此数据类型。但是应用程序异步获取数据,所以实际上 属性 具有未定义的值,然后它具有真实数据:

class SomeClass {
    a: ISomeData;

    constructor() {
        getDataAsync().then((res: ISomeData) => this.a = res);
    }
}

我认为 a: ISomeData 不正确。必须是 a: ISomeData | undefined。 (如果在构造函数中同步设置this.a = someData就正确了) 是否有 tslint 规则来检查 class 属性没有数据并且必须具有未定义的类型?

默认情况下,您分配的任何类型都可以采用值 undefined 和 null 以及您所做的任何类型声明。

在您的 TypeScript 配置文件 (tsconfig.json) 中,您可以将 StrictNullChecks 编译器选项设置为 true。

{
  "compilerOptions": {
    "strictNullChecks": true
  }
}

来自 Compiler Options 上的 TypeScript 文档:

In strict null checking mode, the null and undefined values are not in the domain of every type and are only assignable to themselves and any (the one exception being that undefined is also assignable to void).

当您这样做时,类型为 ISomeData 的变量只能包含该类型。

如果你想要 undefined/null 个值,你必须输入

a: ISomeData | undefined | null;