Skip to content

Instantly share code, notes, and snippets.

@xnuk
Last active September 22, 2020 02:59
Show Gist options
  • Save xnuk/0587ba9bb0302c9f3c27c65aef04d642 to your computer and use it in GitHub Desktop.
Save xnuk/0587ba9bb0302c9f3c27c65aef04d642 to your computer and use it in GitHub Desktop.
// TypeScript Playground: https://www.typescriptlang.org/play?target=99&jsx=0&ts=4.0.2#code/C4TwDgpgBAogjgVwIYBsDOAeA+lCAPYCAOwBM0oAhAGktwOLKgEEamA+KAXiiIgDcIAJwBQw0JCgBJImATAuwqEqgAfKAG8o4iAC4oAciT6aRJAFtdUNMEEBLIgHMoAX0XK1m7Xv0AjY1CQHSyIEMx8hFzclDy1wS30AY38+WzRbHxRLTQS9AEYaMHsIJDAwTO9CgC9KoxdI5VUNWMhvEmTU9PKmkj0AJgKikrL4hIALWwSAa2J9OtcxONg8SATCEgUGmK8DIxNzS2s7RxplQMsEUggAMyKSGhS0jPPLm951102m7d9-Uws9C4ka63GhnPQhMJCE5KB6dZ5A14Qd5RRqeOLeJJ7f5QQHAt6goIAl4gqCwp56bJ5Gg9HHE-FQQq8IZdfRVGqzZz1dxfdEGNpY+F4pEEwWIu6kjrkpo5WkIkk0-oMwalFljCbTIgcyILCRMVbIFBcZhENAAdyEGGksmAbB10AAShA0AgUPJuPADZgYMsIKthcx9agaN6VmtbXbjWaLQAVDjcaNAA
type Equals<_ extends B, B extends A, A> = never
type Input =
| { type: 'a', name: string }
| { type: 'b', age: number }
| { type: 'c', visible: { c: 1, pineapple: 'pizza' } }
| { type: 'd', visible: { d: 2, pineapple: 'chicken' } }
type Expected =
| { type: 'a', name: string, age: undefined, visible: undefined }
| { type: 'b', name: undefined, age: number, visible: undefined }
| { type: 'c', name: undefined, age: undefined, visible: { c: 1, d: undefined, pineapple: 'pizza' } }
| { type: 'd', name: undefined, age: undefined, visible: { c: undefined, d: 2, pineapple: 'chicken' } }
type Actual = Answer<Input>
type Result = Equals<Expected, Actual, Expected>
// type Answer<T> = T
type AllKeys<T> = T extends (infer A | infer B) ? (keyof A | keyof B) : keyof T
type Normalize<T> = { [K in keyof T]: T[K] }
type FillUndefined<T, P> = Normalize<T & { [K in Exclude<AllKeys<P>, keyof T>]: undefined }>
type PreAnswer<T, P = T> = T extends (infer A | infer B) ? (FillUndefined<A, P> | FillUndefined<B, P>) : FillUndefined<T, P>
type Answer<T> = PreAnswer<T>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment