Home > Software engineering >  Conditionally index types with union (getting T[K] where K may not be a key of all types)
Conditionally index types with union (getting T[K] where K may not be a key of all types)

Time:08-11

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

Link to TS Playground

  • Related