Consider the type definition provided below:
type A = { a: string } | { a?: undefined; b: string }
This essentially means that if you include a
, it should be the only property provided. If you do not include or have a
as undefined
, then you also need to provide b
.
The goal is to access b
when a
is undefined in the code snippet below:
let t = true
// The intention with this line of code is to confuse the compiler so it doesn't narrow down the definition just yet.
const z: A = t ? { a: 'a' } : { b: 'b' }
if (z.a) {
console.log(z.a)
} else {
console.log(z.b)
}
However, an error message is received:
Property 'b' does not exist on type 'A'.
Property 'b' does not exist on type '{ a: string; }'
You can find a link to TypeScript Playground with the relevant code.
I'm searching for a type-safe solution without using unsafe methods like hasOwnProperty('b')
or type assertions. Is there a way to achieve this?