前置知识: TypeScript

模板字面量类型

00:00
1 min Advanced 2026/6/14

TypeScript模板字面量类型详解:Template Literal Types与字符串模式匹配。

1. 模板字面量类型基础

1.1 基本语法

type World = 'world';
type Greeting = `hello ${World}`; // 'hello world'

1.2 与联合类型组合

type Color = 'red' | 'blue' | 'green';
type Size = 'small' | 'medium' | 'large';
type CSSClass = `${Size}-${Color}`;
// 'small-red' | 'small-blue' | 'small-green' | 'medium-red' | ...

1.3 内置字符串操作类型

type A = Uppercase<'hello'>; // 'HELLO'
type B = Lowercase<'HELLO'>; // 'hello'
type C = Capitalize<'hello'>; // 'Hello'
type D = Uncapitalize<'Hello'>; // 'hello'

2. 字符串模式匹配

2.1 提取前缀/后缀

type RemovePrefix<S, P extends string> = S extends `${P}${infer Rest}` ? Rest : S;

type A = RemovePrefix<'getUserById', 'get'>; // 'UserById'

2.2 事件监听器类型

type EventName<T extends string> = `on${Capitalize<T>}`;
type Handler<T> = (event: T) => void;

type ClickHandler = Handler<EventName<'click'>>; // (event: 'onClick') => void

2.3 CSS 属性类型

type CSSProperty = 'margin' | 'padding';
type Direction = 'top' | 'right' | 'bottom' | 'left';
type CSSShorthand = `${CSSProperty}-${Direction}`;
// 'margin-top' | 'margin-right' | ...

3. 实战应用

3.1 类型安全的路由

type Routes = '/users' | '/users/:id' | '/posts/:postId/comments';

type Params<T extends string> = T extends `${string}:${infer P}/${infer Rest}`
  ? { [K in P | keyof Params<Rest>]: string }
  : T extends `${string}:${infer P}`
    ? { [K in P]: string }
    : {};

type UserParams = Params<'/users/:id'>; // { id: string }

3.2 类型安全的 API 客户端

type ApiMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type ApiEndpoint = '/users' | '/posts' | '/comments';
type ApiKey = `${ApiMethod} ${ApiEndpoint}`;
// 'GET /users' | 'POST /users' | ...

知识检测

学习进度

-- 已学文档
--% 知识覆盖率

学习推荐

专注模式