javascript - 为什么我在 typescript 中没有收到有关 StrictNullChecks 的警告

标签 javascript typescript 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));

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

我的 typescript 配置如下所示:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "strictNullChecks": true,
    "outDir": "./built"
  },
  "include": [
    "./src/**/*"
  ],
  "exclude": [
    "node_modules"
  ]
}

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

最佳答案

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

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

"strictNullChecks": true,
"strictPropertyInitialization": true,

参见 documentation了解更多信息

--strictNullCheck:

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).

--strictPropertyInitialization

Ensure non-undefined class properties are initialized in the constructor. This option requires --strictNullChecks be enabled in order to take effect.

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

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

关于javascript - 为什么我在 typescript 中没有收到有关 StrictNullChecks 的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53740494/

相关文章:

javascript - 匹配url中特定请求参数的正则表达式

javascript - 代码片段以及箭头函数和普通函数的行为

javascript - Angular 2 应用程序转移到服务层后逻辑无法正常工作

typescript - 导出所有导入的接口(interface)

javascript - jslint 应该只监视全局变量

html - WebStorm 特殊字符编码

javascript - 如何解决 Python Selenium 错误 which

javascript - 为什么以下 javaScript 代码不返回任何元素?

reactjs - 将 React forwardRef 与 Typescript 通用 JSX 参数一起使用

compilation - TypeScript 不会立即在 WebStorm 中转换