字面量类型与索引签名
约 288 字小于 1 分钟
布欧-Lewyon
2026-05-16
首页 › TypeScript › 接口与类型别名 › 字面量类型与索引签名
字面量类型
// 字符串字面量类型
type EventName = 'click' | 'hover' | 'scroll';
type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
// 数字字面量类型
type Port = 3000 | 8080 | 443;
// 布尔字面量类型
type Success = true;模板字面量类型
type Color = 'red' | 'blue';
type Size = 'small' | 'large';
type ProductID = `${Color}-${Size}`;
// "red-small" | "red-large" | "blue-small" | "blue-large"
type EventName = `on${Capitalize<string>}`;
// 任何以 "on" 开头的字符串
// TS 内置字符串操作
type Greeting = `Hello, ${Capitalize<'world' | 'typescript'>}`;
// "Hello, World" | "Hello, TypeScript"Record 与映射类型
// Record<K, V>
type PageInfo = Record<string, { title: string }>;
const pages: PageInfo = {
home: { title: '首页' },
about: { title: '关于' },
};
// Partial / Required / Readonly
type PartialUser = Partial<{ name: string; age: number }>;
// { name?: string; age?: number }小结
| 类型 | 示例 | 场景 |
|---|---|---|
| 字面量类型 | 'click' 3000 true | 精确值约束 |
| 模板字面量 | `${Color}-${Size}` | 组合字符串类型 |
Record<K, V> | Record<string, User> | 字典/映射 |
Partial<T> | Partial<User> | 可选字段 |
上一节:Type 与联合/交叉类型 下一节:函数类型与重载
