为什么我没有在打字稿中收到有关 StrictNullChecks 的警告

Miz*_*lul 6 javascript webstorm typescript

我在打字稿中有以下代码:

interface Member {
    name: string,
    age?: number
}

class Person implements Member {
    name: string;
    constructor(name: string ){
        this.name=name;
    }
}

function bar(person: Member) {
    return "Hello, " + person.name + " " + person.age;
}

let person = new Person("John");
console.log(bar(person));
Run Code Online (Sandbox Code Playgroud)

当我声明 person.age 时,我应该在 bar 函数中收到Object is possible 'undefined'警告,因为不是每个成员都可以有年龄。

我的打字稿配置如下所示:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "strictNullChecks": true,
    "outDir": "./built"
  },
  "include": [
    "./src/**/*"
  ],
  "exclude": [
    "node_modules"
  ]
}
Run Code Online (Sandbox Code Playgroud)

知道为什么这对我不起作用吗?我正在使用 WebStorm 编辑器!

Phi*_*ipp 9

"strict": true,在 tsconfig.json 中打开以启用此警告。

或者,如果您不想要所有需要的严格选项:

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

有关更多信息,请参阅文档

--strictNullCheck

在严格的空检查模式下,null 和 undefined 值并不在每种类型的域中,并且只能分配给它们自己和 any(唯一的例外是 undefined 也可以分配给 void)。

--strictPropertyInitialization

确保在构造函数中初始化非未定义的类属性。此选项需要启用 --strictNullChecks 才能生效。

第二个是你想要的(但需要strictNullChecks工作)

顺便说一句,正如@jayasai amerineni 所提到的,您的示例不应触发此警告。


jay*_*eni 5

strictNullChecks 检查对属性执行的所有操作是否导致非空值。但是在 bar 函数中,它只打印person.age无论是 null 还是 undefined。如果您说person.age.toString()打字稿会引发编译时错误。