【发布时间】: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!
}
here 和 here 已经回答了类似的问题(不满意)。在这两种情况下,答案都需要准确了解要检查的类型,这没有帮助。
我怀疑目前不能做得更好(TS 4.8.4)。如果是这样,那是设计决定还是缺点?
【问题讨论】:
标签: typescript