Forward String literal type of advanced type for TypeScript Foundation
Advanced type
String literal type
The string literal type allows you to specify a fixed value that a string must have. In practical application, the literal type of string can be well matched with union type, type protection and type alias. By using these features together, you can implement strings similar to enumeration types.
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
You can only choose one of the three allowed characters to pass as a parameter. Passing in other values will cause an error.
Argument of type '"uneasy"' is not assignable to parameter of type '"ease-in" | "ease-out" | "ease-in-out"'
String literal types can also be used to distinguish function overloads:
function createElement(tagName: "img"): HTMLImageElement; function createElement(tagName: "input"): HTMLInputElement; // ... more overloads ... function createElement(tagName: string): Element { // ... code goes here ... }
Number literal type
TypeScript also has a numeric literal type.
function rollDie(): 1 | 2 | 3 | 4 | 5 | 6 { // ... }
We seldom use them directly, but they can be used to narrow down the scope of debugging bugs:
function foo(x: number) { if (x !== 1 || x !== 2) { // ~~~~~~~ // Operator '!==' cannot be applied to types '1' and '2'. } }
In other words, when x is compared with 2, its value must be 1, which means that the above comparison check is illegal.
Enumerate member types
As we mentioned in the enumeration section, when every enumeration member is initialized with literal quantity, the enumeration member has type.
When we talk about "Singleton type", we mostly refer to enumeration member type and number / string literal type, although most users will use "Singleton type" and "literal type" interchangeably.