Typescript Union Keys And Make Uncommon Keys Optional

type A = {name: string}
type B = {name: number}
type C = {name: string , age:number}
type D = {name: string , age:string}
type E = {name: string , address:string}

type Prettify<T extends Record<string, unknown>> = { [K in keyof T]: T[K] }

type UnionKeysAndMakeUncommonKeysOptional<
T extends Record<string, unknown>[],
ACC extends Record<string, unknown>={},
UncommonKeyACC extends string = never
> = T extends []
? Prettify<Omit<ACC, UncommonKeyACC> & Partial<Pick<ACC, UncommonKeyACC>>>
: T extends [infer R, ...infer S extends Record<string, unknown>[]]
? UnionKeysAndMakeUncommonKeysOptional<
S,
{ [K in keyof R | keyof ACC]: R[K & keyof R] | ACC[K & keyof ACC] },
Exclude<keyof ACC | keyof R, keyof ACC & keyof R> & string
>
: never


type result = UnionKeysAndMakeUncommonKeysOptional<[A,B,C,D,E]>
// {
// name: string | number;
// age?: string | number;
// address?: string;
// }

playground

require TS 4.7 and set exactOptionalPropertyTypes to true

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Acid Coder

Typescript Zombie. Youtube Pikachu On Acid. (Unrelated to programming but by watching it you become a good developer overnight)