[英]Typescript return if value is undefined
In TypeScript, is it possible to return whether a value is defined (ie not undefined) in such a way, that the transpiler understands that it is not undefined?在 TypeScript 中,是否可以返回值是否已定义(即不是未定义),以使转译器理解它不是未定义的?
To clarify my question, image this example:为了澄清我的问题,想象一下这个例子:
let myVar: MyClass | undefined = /*something*/
if(myVar) {
myVar.foo() // this always works, because the transpiler knows that myVar will never be undefined
}
However, imagine that myVar
needs to be initialized before foo()
can be called.然而,想象一下
myVar
需要在foo()
被调用之前被初始化。 So the if
statement becomes if(myVar && myVar.isInitialized())
.所以
if
语句变成了if(myVar && myVar.isInitialized())
。 But because this check needs to happen in a lot of functions, I wrote the function isUsable()
:但是因为这个检查需要在很多函数中进行,所以我写了 function
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
}
Is it possible to define isUsable()
in such a way, that the transpiler still understands, that myVar
can not be undefined in the if
-Block?是否可以以这样一种方式定义
isUsable()
,使编译器仍然可以理解, myVar
不能在if
-Block 中未定义?
you need a type guard, myVar is MyClass
.你需要一个类型保护,
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.
}
since TS 3.7 you can even assert it.从 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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.