Skip to content

Instantly share code, notes, and snippets.

@jfet97
Last active May 7, 2022 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfet97/45840ab2dcf7012911688fd31d1f9861 to your computer and use it in GitHub Desktop.
Save jfet97/45840ab2dcf7012911688fd31d1f9861 to your computer and use it in GitHub Desktop.
Merge an union of objects with different types for the same properties
type AllKeys<T> = T extends unknown ? keyof T : never
// type Idx<T, K extends PropertyKey> = T extends any ? T[K & keyof T] : never
type Idx<T, K extends PropertyKey> = T extends unknown ? K extends keyof T ? T[K] : never : never;
type MyMerge<T> = { [K in AllKeys<T>]: Idx<T, K> }
// TODO: result of test case must be `{foo: 1 | 2; bar: 3}`
type TestCase1 = MyMerge<{ foo: 1 } | { foo: 2; bar: 3 }>;
// TODO: result of test case must be `{foo: 1 | 2 | 7; bar: 3 | 8}`
type TestCase2 = MyMerge<
{ foo: 1 } | { foo: 2; bar: 3 } | { foo: 7; bar: 8 }
>;
// TODO: result of test case must be `{foo: 1 | 2; bar: 3 | 8}`
type TestCase3 = MyMerge<
{ foo: 1 } | { foo: 2; bar: 3 } | { bar: 8 }
>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment