C.W.K.
Stream
Lesson 05 of 06 · published

Template Literal 타입

~9 min · type-manipulation, template-literals, string-manipulation

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"타입 layer 의 string 연결. Mapped 타입과 결합, key 변환 빌드."

Template literal 타입

Template literal 타입이 runtime template literal 과 같은 backtick 문법 쓰지만, string-literal 타입에 작동. `Hello, ${string}` 가 'Hello, ' 로 시작하는 어떤 string 도 match 하는 타입. `${'a' | 'b'}-${1 | 2}` 가 `'a-1' | 'a-2' | 'b-1' | 'b-2'` 의 union.

이게 타입-레벨 string 조작. Compiler 가 타입 레벨에서 string literal 연결, pattern-match, union 가능 — 그리고 mapped 타입의 key remapping 과 결합, property 이름 체계적으로 변환 가능.

Built-in string utility 타입

TypeScript 가 case 조작용 4개 built-in ship:

  • Uppercase<S>
  • Lowercase<S>
  • Capitalize<S> — 첫 글자 대문자
  • Uncapitalize<S> — 첫 글자 소문자

Template literal 과 결합, '이벤트 핸들러 이름' 같은 타입 빌드: `on${Capitalize<EventName>}` — `'click' | 'hover'` 같은 event 이름 union 에서 `'onClick' | 'onHover'` 얻음.

Template literal 타입이 빛나는 곳

고전 사용은 데이터 모양에서 method 이름 derive 하는 library API. React 의 `useState` setter 가 하나: `useUser` 이름의 hook 에서 setter 가 관례적으로 `setUser`. Template literal 타입이 library 저자가 이걸 타입으로 표현하게 해 — 그리고 compiler 가 관례 따르는지 검증.

Template literal 타입이 library 가 타입 레벨에서 API derive 하는 법. Library 의 타입에 `on${Capitalize<...>}` 보면, event 타입에서 event-handler 이름 빌드 — 그리고 compiler 가 너의 코드가 옳은 이름 쓰는지 체크.

Code

Template literal 타입 — concat, 분배, case-transform·typescript
// 기본 template literal 타입.
type Greeting = `Hello, ${string}`;
const g1: Greeting = 'Hello, Pippa';   // ✅
const g2: Greeting = 'Hi there';        // ❌ 'Hello, ' 로 시작 안 함

// Union 분배.
type CSSValue = `${number}px` | `${number}rem` | `${number}%`;
const v: CSSValue = '12px';            // ✅
const v2: CSSValue = '1.5rem';         // ✅

// Cartesian product.
type Suit = 'hearts' | 'spades' | 'diamonds' | 'clubs';
type Rank = 'A' | 'K' | 'Q' | 'J';
type Card = `${Rank}-of-${Suit}`;       // 총 16 literal 타입

// Built-in case utility.
type A = Uppercase<'hello'>;            // 'HELLO'
type B = Capitalize<'name'>;            // 'Name'

// Event 이름에서 event handler 이름.
type EventName = 'click' | 'hover' | 'focus';
type Handler = `on${Capitalize<EventName>}`;
// 'onClick' | 'onHover' | 'onFocus'

External links

Exercise

type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' 주어지면, type Handler = 'handleGet' | 'handlePost' | 'handlePut' | 'handleDelete' 빌드. 그다음 type Action = '${Method}_USER' | '${Method}_POST' — method 와 entity 의 cartesian product 빌드.
Hint
<code>type Handler = handle${Capitalize&lt;Lowercase&lt;Method&gt;&gt;}</code> — 먼저 method lowercase, 그다음 첫 글자 capitalize. Cartesian product 는 한 타입의 template literal 두 개.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.