我在 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/