strictNullChecks 开启
启用 strictNullChecks
时,当值为 null
或 undefined
时,您需要在对该值使用方法或属性之前测试这些值。 就像在使用可选属性之前检查 undefined
一样,我们可以使用缩小来检查可能是 null
的值:
With strictNullChecks
on, when a value is null
or undefined
, you will need to test for those values before using methods or properties on that value. Just like checking for undefined
before using an optional property, we can use narrowing to check for values that might be null
:
function doSomething(x: string | null) {
if (x === null) {
// do nothing
} else {
console.log("Hello, " + x.toUpperCase());
}
}