typescript 팁 - 서로소 유니온 만들기

👊0👊·2020년 12월 28일
0
/** components */
export * from './modules/Artwork';
export { default as Artwork } from './modules/Artwork';
export * from './modules/ButtonBox';
export { default as ButtonBox } from './modules/ButtonBox';
export * from './modules/CardEventInfoList';
export { default as CardEventInfoList } from './modules/CardEventInfoList';

/** union.ts */

import * as components from 'components';

type FirstArgument<T> = T extends (arg1: infer U, ...args: any[]) => any ? U : any;
type ModuleName = keyof typeof components;
type ModuleRecord = {
  [name in ModuleName]: {
    id?: string;
    name: name;
    props: FirstArgument<typeof components[name]>;
  };
};
  
type DisjointUnionType = ModuleRecord[keyof ModuleRecord];

요러면 아래같은 타입을 쉽게 만들 수 있다.

type ModuleGeneratorProps = {
    id?: string;
    name: "Artwork";
    props: components.ArtworkProps;
} | {
    id?: string;
    name: "ButtonBox";
    props: components.ButtonBoxProps;
} | {
    id?: string;
    name: "CardEventInfoList";
    props: components.CardEventInfoListProps;
} ... more

좀 더 간단한 방법은 나중에 고민하면 좋을 듯

profile
ㅎㅎ

0개의 댓글