TypeScript 数字字面量类型
介绍
在 TypeScript 中,数字字面量类型是一种特殊的类型,它允许你将变量的值限制为特定的数字。与普通的 number
类型不同,数字字面量类型只能接受特定的数值。这种类型在需要精确控制变量取值范围时非常有用,例如在处理状态码、枚举值或特定配置时。
基本用法
数字字面量类型的定义非常简单,只需将具体的数字作为类型即可。例如:
typescript
let statusCode: 200 | 404 | 500;
statusCode = 200; // 合法
statusCode = 404; // 合法
statusCode = 500; // 合法
statusCode = 400; // 错误:Type '400' is not assignable to type '200 | 404 | 500'.
在上面的例子中,statusCode
只能被赋值为 200
、404
或 500
,其他值会导致编译错误。
实际应用场景
1. 状态码处理
在处理 HTTP 请求时,我们通常需要处理不同的状态码。使用数字字面量类型可以确保我们只处理预期的状态码,避免意外的值。
typescript
function handleResponse(statusCode: 200 | 404 | 500) {
if (statusCode === 200) {
console.log("请求成功");
} else if (statusCode === 404) {
console.log("资源未找到");
} else if (statusCode === 500) {
console.log("服务器错误");
}
}
handleResponse(200); // 输出: 请求成功
handleResponse(404); // 输出: 资源未找到
handleResponse(500); // 输出: 服务器错误
handleResponse(400); // 错误:Argument of type '400' is not assignable to parameter of type '200 | 404 | 500'.
2. 枚举替代方案
在某些情况下,你可能不想使用 enum
类型,而是希望使用数字字面量类型来定义一组常量。这种方式更加轻量级,并且可以直接与数字进行比较。
typescript
const Status = {
Success: 200,
NotFound: 404,
ServerError: 500,
} as const;
type StatusType = typeof Status[keyof typeof Status];
function handleStatus(status: StatusType) {
if (status === Status.Success) {
console.log("成功");
} else if (status === Status.NotFound) {
console.log("未找到");
} else if (status === Status.ServerError) {
console.log("服务器错误");
}
}
handleStatus(Status.Success); // 输出: 成功
handleStatus(404); // 输出: 未找到
handleStatus(500); // 输出: 服务器错误
handleStatus(400); // 错误:Argument of type '400' is not assignable to parameter of type '200 | 404 | 500'.
3. 配置选项
在处理配置选项时,数字字面量类型可以确保配置项的值在预期范围内。
typescript
type LogLevel = 0 | 1 | 2 | 3;
function setLogLevel(level: LogLevel) {
console.log(`设置日志级别为: ${level}`);
}
setLogLevel(0); // 输出: 设置日志级别为: 0
setLogLevel(1); // 输出: 设置日志级别为: 1
setLogLevel(4); // 错误:Argument of type '4' is not assignable to parameter of type '0 | 1 | 2 | 3'.
总结
TypeScript 的数字字面量类型是一种强大的工具,它允许你将变量的值限制为特定的数字。通过这种方式,你可以在编译时捕获潜在的错误,并确保代码的健壮性。无论是处理状态码、枚举值还是配置选项,数字字面量类型都能提供额外的安全保障。
附加资源
练习
- 定义一个类型
Direction
,它只能接受0
、1
、2
、3
四个值,分别代表“上”、“下”、“左”、“右”。 - 编写一个函数
move
,接受一个Direction
类型的参数,并根据方向输出移动的方向。 - 尝试将一个不在
Direction
类型中的值传递给move
函数,观察 TypeScript 的编译错误。
typescript
type Direction = 0 | 1 | 2 | 3;
function move(direction: Direction) {
if (direction === 0) {
console.log("向上移动");
} else if (direction === 1) {
console.log("向下移动");
} else if (direction === 2) {
console.log("向左移动");
} else if (direction === 3) {
console.log("向右移动");
}
}
move(0); // 输出: 向上移动
move(1); // 输出: 向下移动
move(4); // 错误:Argument of type '4' is not assignable to parameter of type 'Direction'.