类型系统
字面量类型
使用字符串、数字字面量作为类型,结合联合类型
字面量类型
字面量类型让你把具体值作为类型,配合联合类型实现精确的类型约束。
学完本章你将: 掌握字符串、数字字面量类型和 as const。
字符串字面量类型
typescript
// 限定为具体值
let direction: "up" | "down" | "left" | "right";
direction = "up"; // ✅
// direction = "forward"; // ❌
// 实战:HTTP 方法
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
function request(url: string, method: HttpMethod): void {
console.log(`${method} ${url}`);
}
request("/api/users", "GET"); // ✅
// request("/api/users", "OPTIONS"); // ❌
数字字面量类型
typescript
// 骰子点数
type DiceValue = 1 | 2 | 3 | 4 | 5 | 6;
function rollDice(): DiceValue {
return Math.ceil(Math.random() * 6) as DiceValue;
}
// HTTP 状态码
type SuccessCode = 200 | 201 | 204;
type ClientError = 400 | 401 | 403 | 404;
type ServerError = 500 | 502 | 503;
type HttpStatus = SuccessCode | ClientError | ServerError;
as const 断言
typescript
// 普通声明 —— 类型变宽
const colors1 = ["red", "green", "blue"];
// 类型:string[]
// as const —— 字面量类型
const colors2 = ["red", "green", "blue"] as const;
// 类型:readonly ["red", "green", "blue"]
type Color = (typeof colors2)[number]; // "red" | "green" | "blue"
// 对象
const config = {
api: "https://api.example.com",
timeout: 5000,
retries: 3,
} as const;
// 类型:
// { readonly api: "https://api.example.com";
// readonly timeout: 5000;
// readonly retries: 3; }
实战场景
typescript
// 配置对象
const sizes = ["small", "medium", "large"] as const;
type Size = (typeof sizes)[number];
// 映射表
const statusMap = {
idle: "空闲",
loading: "加载中",
success: "成功",
error: "出错",
} as const;
type Status = keyof typeof statusMap; // "idle" | "loading" | "success" | "error"
type StatusText = (typeof statusMap)[Status]; // "空闲" | "加载中" | "成功" | "出错"
function getStatusText(status: Status): StatusText {
return statusMap[status];
}