给定以下类型定义:
type A = { a: string } | { a?: undefined; b: string }
这基本上意味着,如果您提供a
,那么这就是您应该提供的全部内容.如果您没有提供a
,或者您提供了a
但它是undefined
,则您还必须提供b
如果根据下面的代码未定义a
,我希望能够访问b
:
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; }'
这里有一个link to ts的playground ,带有相关代码.
我期待一个类型安全的解决方案.即不使用不安全字符串(例如hasOwnProperty('b')
)测试属性存在性,也不使用类型断言.
这可能吗?