看下面这个例子:
let x: "hello" = "hello";
// OK
x = "hello";
// ...
x = "howdy";
"hello" 也能扮演一个匿名类型的角色。

但是通过将文字组合成联合,你可以表达一个更有用的概念——例如,只接受一组特定已知值的函数:

function printText(s: string, alignment: "left" | "right" | "center") {
console.log(s, alignment);
}
printText("Hello, world", "left");
printText("G'day, mate", "centre");
现在,printText 函数的 alignment 参数,只接受 left,right,和 center 这三个值。类似其他编程语言里的枚举类型。
可以和 interface 或者 type alias 混用:
interface Options {
width: number;
}
function configure(x: Options | "auto") {
// ...
}
configure({ width: 100 });
configure("auto");
configure("automatic");

更多Jerry的原创文章,尽在:"汪子熙":

网友评论