템플릿 리터럴 타입
JavaScript의 백틱(`` \` ``) 문자열 템플릿을 TypeScript의 타입 시스템에서도 사용할 수 있습니다. 이를 템플릿 리터럴 타입(Template Literal Types)이라고 부릅니다.
유니온 타입을 결합하면 수학의 곱셈(Cartesian Product)처럼 작동하여 수많은 문자열 조합을 단 한 줄의 코드로 생성해 냅니다.
<!-- ==========================================
// 📂 ts-advanced/template-literal.ts
// ========================================== -->
<script>
type VerticalAlignment = "top" | "middle" | "bottom";
type HorizontalAlignment = "left" | "center" | "right";
// 1. 유니온 타입을 템플릿 리터럴로 결합하면 3x3 = 9개의 타입이 한 번에 생성됩니다.
type Alignment = `${VerticalAlignment}-${HorizontalAlignment}`;
/* 결과:
"top-left" | "top-center" | "top-right" |
"middle-left" | "middle-center" | "middle-right" |
"bottom-left" | "bottom-center" | "bottom-right"
*/
const btnPosition: Alignment = "bottom-right"; // OK
// const btnPosition2: Alignment = "center-top"; // ❌ Error (순서 틀림)
// 2. 실무 예제: Mapped Type과 결합하여 이벤트 핸들러 이름 자동 생성
type Store = {
user: string;
theme: string;
};
// TS 내장 유틸리티 Capitalize를 사용해 첫 글자를 대문자로 변경합니다.
// as 키워드를 사용해 Mapped Type의 키 이름을 재지정(Key Remapping)합니다.
type StoreEvents = {
[K in keyof Store as `on${Capitalize<K>}Change`]: (newValue: Store[K]) => void;
};
/* 결과:
type StoreEvents = {
onUserChange: (newValue: string) => void;
onThemeChange: (newValue: string) => void;
}
*/
</script>