Skip to content

Instantly share code, notes, and snippets.

@fostyfost
Created July 28, 2022 13:26
Show Gist options
  • Save fostyfost/d00df05e82b385f50f6e8550959f7095 to your computer and use it in GitHub Desktop.
Save fostyfost/d00df05e82b385f50f6e8550959f7095 to your computer and use it in GitHub Desktop.
Union to Type
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