轉發TypeScript基礎入門之高級類型的字符串字面量類型app
字符串字面量類型容許你指定字符串必須的固定值。 在實際應用中,字符串字面量類型能夠與聯合類型,類型保護和類型別名很好的配合。 經過結合使用這些特性,你能夠實現相似枚舉類型的字符串。函數
type Easing = "ease-in" | "ease-out" | "ease-in-out"; class UIElement { animate(dx: number, dy: number, easing: Easing) { if (easing === "ease-in") { // ... } else if (easing === "ease-out") { } else if (easing === "ease-in-out") { } else { // error! should not pass null or undefined. } } } let button = new UIElement(); button.animate(0, 0, "ease-in"); button.animate(0, 0, "uneasy"); // error: "uneasy" is not allowed here
你只能從三種容許的字符中選擇其一來作爲參數傳遞,傳入其它值則會產生錯誤。spa
Argument of type '"uneasy"' is not assignable to parameter of type '"ease-in" | "ease-out" | "ease-in-out"'
字符串字面量類型還能夠用於區分函數重載:調試
function createElement(tagName: "img"): HTMLImageElement; function createElement(tagName: "input"): HTMLInputElement; // ... more overloads ... function createElement(tagName: string): Element { // ... code goes here ... }
TypeScript還具備數字字面量類型。code
function rollDie(): 1 | 2 | 3 | 4 | 5 | 6 { // ... }
咱們不多直接這樣使用,但它們能夠用在縮小範圍調試bug的時候:blog
function foo(x: number) { if (x !== 1 || x !== 2) { // ~~~~~~~ // Operator '!==' cannot be applied to types '1' and '2'. } }
換句話說,當x與2進行比較的時候,它的值必須爲1,這就意味着上面的比較檢查是非法的。ip
如咱們在 枚舉一節裏提到的,當每一個枚舉成員都是用字面量初始化的時候枚舉成員是具備類型的。字符串
在咱們談及「單例類型」的時候,多數是指枚舉成員類型和數字/字符串字面量類型,儘管大多數用戶會互換使用「單例類型」和「字面量類型」。get