Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use conditional types:

type A = {
    one: 'a' | 'b'
}

type B = {
    two: 'c' | 'd'
}

type MakeBoth<T, K extends string> = T extends  Record<K, unknown> ? T[K] : undefined
type Both = MakeBoth<A | B, 'two'>
// 'c' | 'd' | undefined

Link to TS Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading