TypeScript 템플릿 리터럴 타입(Template Literal Types)은 문자열 타입을 조합하고 변환하는 기능이다. JavaScript 템플릿 리터럴과 동일한 문법으로 타입 수준에서 동작한다.
기본 문법
typescript
type Greeting = `Hello, ${string}!`;
const a: Greeting = 'Hello, World!'; // OK
const b: Greeting = 'Hi, World!'; // Error
type Direction = 'top' | 'bottom' | 'left' | 'right';
type CSSProperty = `margin-${Direction}`;
// 'margin-top' | 'margin-bottom' | 'margin-left' | 'margin-right'
유니온 조합
typescript
type EventName = 'click' | 'focus' | 'blur';
type Handler = `on${Capitalize<EventName>}`;
// 'onClick' | 'onFocus' | 'onBlur'
type Color = 'red' | 'blue';
type Size = 'sm' | 'md' | 'lg';
type Variant = `${Color}-${Size}`;
// 'red-sm' | 'red-md' | 'red-lg' | 'blue-sm' | 'blue-md' | 'blue-lg'
내장 문자열 변환 타입
typescript
type U = Uppercase<'hello'>; // 'HELLO'
type L = Lowercase<'HELLO'>; // 'hello'
type C = Capitalize<'hello'>; // 'Hello'
type UC = Uncapitalize<'Hello'>; // 'hello'
typescript
// 이벤트 이름에서 핸들러 추출
type EventHandler<T extends string> =
T extends `on${infer Event}` ? Lowercase<Event> : never;
type Click = EventHandler<'onClick'>; // 'click'
type Focus = EventHandler<'onFocus'>; // 'focus'
// 경로 파라미터 추출
type PathParams<T extends string> =
T extends `${infer _}/:${infer Param}/${infer Rest}`
? Param | PathParams<`/${Rest}`>
: T extends `${infer _}/:${infer Param}`
? Param
: never;
type Params = PathParams<'/users/:id/posts/:postId'>;
// 'id' | 'postId'
실용 패턴
typescript
// 이벤트 에미터 타입 안전성
type Events = { userCreated: User; orderPlaced: Order };
type Emitter = {
on<K extends keyof Events>(event: K, cb: (data: Events[K]) => void): void;
emit<K extends keyof Events>(event: K, data: Events[K]): void;
};
관련 개념