美文网首页
巧用 TypeScript Literal Types 模拟枚举

巧用 TypeScript Literal Types 模拟枚举

作者: 华山令狐冲 | 来源:发表于2021-08-09 09:08 被阅读0次

看下面这个例子:

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的原创文章,尽在:"汪子熙":


相关文章

网友评论

      本文标题:巧用 TypeScript Literal Types 模拟枚举

      本文链接:https://www.haomeiwen.com/subject/nfzwyltx.html