TypeScript 2

TypeScript - Union Type 정의와 사용법 간단 정리

Union Type 이란? Union Type은 두 개 이상의 타입을 조합해서 정의한 타입이다. 예를 들어 다수의 자료형이 있으면, interface Square { kind: 'square' size: number } interface Rectangle { kind: 'rectangle' width: number height: number } interface Circle { kind: 'circle' radius: number } Union Type은 이렇게 |로 구분해서 정의한다. type Shape = Square | Rectangle | Circle Union Type의 타입 추론 TypeScript에서는 타입 추론(type inference)을 통해 각 타입을 추론하게 된다. TypeScrip..

[TS] props에 허용하는 클래스명 강제하기

서사 컴포넌트 Props에 tailwindcss의 클래스명을 받을 때가 있다. 타입 선언할 때 단순하게 string으로만 정의하기도 하는데, string으로 정의해서 의도하지 않게 버그가 발생하는 경우가 있었다. 예를 들어서 아이콘 컴포넌트에서 w-*, h-*를 함께 받아야 하는데, string으로만 정의하면 컴파일 타임에 알 수 없다. 타입스크립트의 탬플릿 리터럴과 infer를 활용하면 사용하면 안되는 클래스명과 쌍으로 사용해야 하는 클래스명을 타입을 통해 알 수 있다. Tailwind ClassName fill-* 대신 text- 사용하도록 처리 fill-*를 사용하면 text-*로 사용하라고 알려준다. T extends `${infer U}fill${infer V}` ? `${U}text${V}` ..

728x90