字面量类型
目前 TypeScript 中有三种可用的字面量类型集合,分别是:字符串、数字和布尔值。通过使用字面量类型,你可以规定一个字符串、数字或布尔值必须含有的确定值。
当你通过 var
或 let
来声明一个变量时,实际上你在告诉编译器这个变量中的内容有可能会被改变。与之相对地,用 const
来声明对象会让 TypeScript 知道这个对象永远不会被改变。
字面量类型可以通过联合联系、类型守卫、类型别名来结合实际字符串值。通过这些特性,我们可以获取一种字符串并使其有类似枚举(enum)的行为。
type Easing = "ease-in" | "ease-out" | "ease-in-out";
class UIElement {
animate(dx: number, dy: number, easing: Easing) {
// ...
} else if (easing === "ease-in-out") {
} else {
// It's possible that someone could reach this
// by ignoring your types though.
}
}
}
let button = new UIElement();
button.animate(0, 0, "ease-in");
你可以传递三种允许的字符串,但是如果传递其他的字符串会收到如下错误:
function createElement(tagName: "img"): HTMLImageElement;
function createElement(tagName: "input"): HTMLInputElement;
// ... more overloads ...
function createElement(tagName: string): Element {
// ... code goes here ...
}
TypeScript 还有数字字面量类型,它的行为和上述字符串字面量类型相同。
数字字面量类型经常用来描述配置值:
interface MapConfig {
lng: number;
lat: number;
tileSize: 8 | 16 | 32;
}
setupMap({ lng: -73.935242, lat: 40.73061, tileSize: 16 });