给出以下类型定义:
type A = { a: string } | { a?: undefined; b: string }
这基本上意味着,如果您提供a
,那就是您应该提供的全部内容。如果您不提供a
,或者您提供a
了,那么undefined
您还必须提供b
我希望能够根据下面的代码访问b
if is undefined :a
let t = true
// The purpose in this line of code is to confuse the compiler such that it won't narrow the definition right in this line of code.
const z: A = t ? { a: 'a' } : { b: 'b' }
if (z.a) {
console.log(z.a)
} else {
console.log(z.b)
}
我收到的是以下错误消息::
Property 'b' does not exist on type 'A'.
Property 'b' does not exist on type '{ a: string; }'
这里是ts Playground 的链接以及相关代码。
我期待一个类型安全的解决方案。即不使用不安全字符串(例如)来测试属性是否存在,hasOwnProperty('b')
并且不使用类型断言。
那可能吗?
您收到该错误消息的原因是,可以进入 else 块并且
z.a
属性上仍然有一个字符串。z.a
如果是空字符串,就会发生这种情况""
。所以事实上,在 else 情况下,类型根本没有缩小。如果你将其切换到此,它将起作用:
游乐场链接
您的检查应该更明确:
您的代码不起作用的原因可能
z.a
是''
,它是一个字符串,但是是假的,这会导致 else 分支被用于没有z.b
...