Given a union of two (or more) types, I need to get an "index type" of a property that may only exists on one of the types:
type A = {
one: 'a' | 'b'
}
type B = {
two: 'c' | 'd'
}
type Both = A | B;
type X = Both['two'];
// expected: 'c' | 'd' | undefined
// actual: Error: Property 'two' does not exist on type 'Both'.
I understand why this is happening in the above code, but it seems like there should be some way to get "expected" result.
I tried conditional types, but ultimately couldn't figure it out...
CodePudding user response:
You can use conditional types:
type A = {
one: 'a' | 'b'
}
type B = {
two: 'c' | 'd'
}
type Maybe<T, K extends string> = T extends {[P in K]?: unknown} ? T[K] : undefined
type Both = Maybe<A | B, 'two'>
// 'c' | 'd' | undefined