Typescript 类型脚本类型推断不适用于函数类型保护
在Typescript 类型脚本类型推断不适用于函数类型保护,typescript,Typescript,在alpha中,我检查结果是否为null,如果是,则抛出新错误,但comiler仍显示编译错误: const obj = { objMethod: function (): string | null { return 'always a string'; }, }; function alpha() { if (obj.objMethod() === null) { throw new Error('type guard, but compiler does n
alpha
中,我检查结果是否为null
,如果是,则抛出新错误
,但comiler仍显示编译错误:
const obj = {
objMethod: function (): string | null {
return 'always a string';
},
};
function alpha() {
if (obj.objMethod() === null) {
throw new Error('type guard, but compiler does not count it as one :( ');
}
const beta: string = obj.objMethod();
console.log(beta);
}
但这段代码运行得非常好:
const obj = {
objMethod: function (): string | null {
return 'always a string';
},
};
function alpha() {
const result = obj.objMethod();
if (result === null) {
throw new Error('this DOES count as a type guard. ');
}
const beta: string = result; // no error
console.log(beta);
}
Typescript无法证明您的
objMethod
总是返回相同的值。它可以在第一次调用时返回非null值,在第二次调用时返回null值。如果将其分配给常量变量,则该检查将断言该变量不为null。由于变量为常量,赋值后该值不能更改,因此,如果通过检查,则该值必须为非null