字面量类型限制变量的值必须是某个确切的值。换句话说,字面量类型只允许一个确切的值,而不是一种范围的值。
字面量类型常见于字符串、数字和布尔值。
例如,以下代码定义了一个名为**direction
**的字符串字面量类型,该类型只能包括特定的字符串值:
type Direction = "north" | "south" | "east" | "west";
let dir: Direction;
dir = "north"; // 正确
dir = "southeast"; // 错误,不在定义的字面量类型中
数字字面量类型与字符串字面量类型类似,但用于数字值:
type DiceValue = 1 | 2 | 3 | 4 | 5 | 6;
let value: DiceValue;
value = 4; // 正确
value = 7; // 错误,不在定义的字面量类型中
布尔字面量类型较少用,因为布尔值本身只有两个可能的值,但你仍可以为变量限制为其中一个:
type TrueOnly = true;
let value: TrueOnly;
value = true; // 正确
value = false; // 错误,不在定义的字面量类型中
你可以将字面量类型和非字面量类型结合起来使用
interface Options {
width: number;
}
function configure(x: Options | "auto") {
// ...
}
configure({ width: 100 });
configure("auto");
configure("automatic"); // Argument of type '"automatic"' is not assignable to parameter of type 'Options | "auto"'.
x既可以是Options接口的类型,也可以是值为“auto”的字面量类型
使用对象初始化变量时,TypeScript 假定该对象的属性稍后可能会更改值。例如,如果您编写如下代码:
const obj = { counter: 0 };
if (someCondition) {
obj.counter = 1;
}