简体   繁体   English

Typescript 中的类型断言和可选链接

[英]Type assertions and optional chaining in Typescript

I have the following function that performs a simple type assertion, checking that a variable is not undefined or null.我有以下 function 执行简单的类型断言,检查变量是否未定义或 null。

const isDefinedAndNotNull = <T>(val: T | null | undefined): val is NonNullable<T> =>
    (val !== null) && (typeof val !== "undefined");

However, I have an issue when using this function to assert the presence of a nested object using optional chaining.但是,当使用此 function 使用可选链接断言嵌套 object 的存在时,我遇到了问题。 The below code will cause Typescript to not compile:以下代码将导致 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
}

However, Typescript has no problem with the following:但是,Typescript 没有以下问题:

if (thing?.myProp?.coolThing) {
    console.log(thing.myProp.coolThing); // defined here
}

My question is essentially how to get the type assertion to assert that both the nested object and the target object are defined, if this is possible.我的问题本质上是如何让类型断言断言嵌套的 object 和目标 object 都已定义,如果可能的话。 Thanks!谢谢!

Link to a TS Playground containing the above code 链接到包含上述代码的 TS Playground

The type assertion only really covers the deepest level;类型断言只真正涵盖了最深层次; the property you're passing to the assertion.您传递给断言的属性。
Your condition only confirms coolThing is defined and not null .您的情况确认coolThing已定义,而不是null

To cover myProp , you'd need to explicitly check that as well:要涵盖myProp ,您还需要明确检查:

if (isDefinedAndNotNull(thing?.myProp) && isDefinedAndNotNull(thing?.myProp?.coolThing)) {
  console.log(thing.myProp.coolThing);
}

TS is naïve like that, and I honestly don't know of a way around it. TS就是那样天真,老实说,我不知道有什么办法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM