在TypeScript中,是否可以返回值是否已定义(即未定义),以使编译器理解该值不是未定义的?
为澄清我的问题,请为以下示例成像:
let myVar: MyClass | undefined = /*something*/
if(myVar) {
myVar.foo() // this always works, because the transpiler knows that myVar will never be undefined
}
但是,假设在调用myVar
之前需要初始化foo()
。因此,if
语句变为if(myVar && myVar.isInitialized())
。但是由于此检查需要在许多函数中进行,因此我编写了函数isUsable()
:
function isUsable(myVar: MyClass | undefined): boolean {
return myVar && myVar.isInitialized();
}
let myVar: MyClass | undefined = /*something*/
if(isUsable(myVar)) {
myVar.foo() // this does not work, because myVar may be undefined. I would have to use myVar?.foo() or myVar!.foo() which I want to avoid
}
是否可以以这样的方式定义isUsable()
,以便编译器仍然理解myVar
不能在if
块中未定义?
答案 0 :(得分:2)
您需要一个类型保护myVar is MyClass
。
function isUsable(myVar: MyClass | undefined): myVar is MyClass {
return myVar && myVar.isInitialized();
}
let myVar: MyClass | undefined;
if(isUsable(myVar)) {
myVar.foo(); // now it works.
}
自TS 3.7起,您甚至可以声明它。
function isUsable(myVar: MyClass | undefined): asserts myVar is MyClass {
if (!myVar || !myVar.isInitialized()) {
throw new Error();
}
}
let myVar: MyClass | undefined;
isUsable(myVar);
myVar.foo(); // now it works.