Reputation: 1672
I can get all keys of a union by type UnionKeys<T> = { [Key in keyof T]: Key }[keyof T]
type MyUnion = {x: 'a', y: 'b'} | {x: 'aa', z: 'c'}
type T1 = UnionKeys<MyUnion> // 'x' | 'y' | 'z'
How do I get the merged type of a union?
type MergedUnion<T> = ?????
type T2 = MergedUnion<MyUnion> // `{x: 'a' | 'aa', y: 'b', z: 'c'}`
Upvotes: 1
Views: 128
Reputation: 249536
This can be done. We map over UnionKeys
( I used a different definition, using distributive conditional types) and we use another distributive conditional type to extract a union of all values that a specific key can have:
type MyUnion = {x: 'a', y: 'b'} | {x: 'aa', z: 'c'}
type UnionKeys<T> = T extends unknown ? keyof T : never;
type UnionValues<T, K extends PropertyKey> = T extends Record<K, infer U> ? U: never;
type MergedUnion<T> = { [P in UnionKeys<T>]: UnionValues<T, P> }
Upvotes: 2