巧用 TypeScript Literal Types 模拟枚举类型
生活随笔
收集整理的這篇文章主要介紹了
巧用 TypeScript Literal Types 模拟枚举类型
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
看下面這個例子:
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 模拟枚举类型的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 生产无人机的股票有哪些
- 下一篇: 熟女猎人银枪《红雀2》技巧攻略之瑞贝卡