[英]Type assertions and optional chaining in Typescript
我有以下 function 执行简单的类型断言,检查变量是否未定义或 null。
const isDefinedAndNotNull = <T>(val: T | null | undefined): val is NonNullable<T> =>
(val !== null) && (typeof val !== "undefined");
但是,当使用此 function 使用可选链接断言嵌套 object 的存在时,我遇到了问题。 以下代码将导致 Typescript 无法编译:
type MaybeNullThing = {
myProp?: {
coolThing?: string
}
}
const thing: MaybeNullThing = getThing();
if (isDefinedAndNotNull(thing?.myProp?.coolThing)) {
console.log(thing.myProp.coolThing); // error: thing.myProp could be undefined
}
但是,Typescript 没有以下问题:
if (thing?.myProp?.coolThing) {
console.log(thing.myProp.coolThing); // defined here
}
我的问题本质上是如何让类型断言断言嵌套的 object 和目标 object 都已定义,如果可能的话。 谢谢!
类型断言只真正涵盖了最深层次; 您传递给断言的属性。
您的情况仅确认coolThing
已定义,而不是null
。
要涵盖myProp
,您还需要明确检查:
if (isDefinedAndNotNull(thing?.myProp) && isDefinedAndNotNull(thing?.myProp?.coolThing)) {
console.log(thing.myProp.coolThing);
}
TS就是那样天真,老实说,我不知道有什么办法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.