小编Mat*_*ead的帖子

Typescript 可以根据字段存在(未定义/不存在)而不是值来保护/区分吗?

谁能解释为什么 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

1
推荐指数
1
解决办法
972
查看次数