Created
July 28, 2022 13:26
-
-
Save fostyfost/d00df05e82b385f50f6e8550959f7095 to your computer and use it in GitHub Desktop.
Union to Type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type UnionToType< | |
U extends Record<string, unknown> | |
> = { | |
[K in (U extends unknown ? keyof U : never)]: U extends unknown | |
? K extends keyof U ? U[K] : never | |
: never | |
} | |
type A = { | |
a: string | |
} | |
type B = { | |
b: number | |
} | |
type C = { | |
c: boolean | |
} | |
type D = { | |
c: A | |
} | |
type Combined = UnionToType<A | B | C | D> | |
/* | |
type Combined = { | |
a: string; | |
b: number; | |
c: boolean | A; | |
} | |
*/ | |
const combined1: Combined = { | |
a: 'test', | |
b: 2, | |
c: { | |
a: '' | |
} | |
} | |
const combined2: Combined = { | |
a: 'test', | |
b: 2, | |
c: false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment