Typescript 유니온 키 및 흔하지 않은 키를 선택 사항으로 만들기

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

TS 4.7이 필요하고 exactOptionalPropertyTypes를 true로 설정

좋은 웹페이지 즐겨찾기