【问题标题】:Why does narrowing the type of a child property not remove undefined/null from parent object's type?为什么缩小子属性的类型不会从父对象的类型中删除 undefined/null?
【发布时间】:2022-10-13 15:21:12
【问题描述】:

我想知道为什么这段代码的行为如此,如果可能的话,如何修复它:

interface Optional {
    opt?: string
}

function isNullOrUndefined<T>(val: T | null | undefined): val is null | undefined {
    return val === null || val === undefined;
}

const x: Optional | undefined = Math.random() > 0.5 ? undefined : { opt: 'hoho' };

if (!isNullOrUndefined(x?.opt)) {
    const y: string = x.opt // Error, even though it should be clear that x is defined
}

if (!isNullOrUndefined(x?.opt)) {
    const y: string = x!.opt // No error, TS knows that child exists. So parent must also exist!
}

Playground

herehere 已经回答了类似的问题(不满意)。在这两种情况下,答案都需要准确了解要检查的类型,这没有帮助。

我怀疑目前不能做得更好(TS 4.8.4)。如果是这样,那是设计决定还是缺点?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    这是因为您需要缩小 x 的类型:

    使固定:

    if (typeof x !== 'undefined' && !isNullOrUndefined(x.opt)) {
        const y: string = x.opt
    }
    

    修复细分:

    if (typeof x !== 'undefined' && x.opt !== null && typeof x.opt !== 'undefined') {
        const z: string = x.opt
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 2019-07-16
      • 2017-12-24
      • 1970-01-01
      相关资源
      最近更新 更多