谁能解释为什么 Typescript 可以使用in关键字缩小类型,但不能通过存在非未定义的值来缩小类型?我正在将一个大型代码库从 JS 移植到 TS,并且对该结构进行了非常广泛的使用if (x.something) { ... }。
declare const x: { a?: object } | { b: number };
if ('a' in x) {
const Q = x.a; // Q: object | undefined, correct but not very helpful - still have to test Q for non-undefined
}
if (x.a) {
const Q = x.a; // Doesn't work, but if it did, Q: object, which is helpful
}
if (typeof x.a !== "undefined") { …Run Code Online (Sandbox Code Playgroud) undefined discriminated-union typescript type-narrowing union-types