天天看點

巧用 TypeScript Literal Types 模拟枚舉類型

看下面這個例子:

let x: "hello" = "hello";
// OK
x = "hello";
// ...
x = "howdy";
           

“hello” 也能扮演一個匿名類型的角色。

巧用 TypeScript Literal Types 模拟枚舉類型

但是通過将文字組合成聯合,你可以表達一個更有用的概念——例如,隻接受一組特定已知值的函數:

巧用 TypeScript Literal Types 模拟枚舉類型
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");
           

繼續閱讀