Literal Types
Literal types in TypeScript allow you to specify that a variable can only have one or more exact values, rather than any value of a broader type like string or number. This restriction helps prevent errors by ensuring that only expected values are used in your code.
1234567891011// String literal type let direction: "left" | "right" | "up" | "down"; direction = "left"; // OK direction = "up"; // OK // direction = "forward"; // Error: Type '"forward"' is not assignable to type '"left" | "right" | "up" | "down"' // Number literal type let diceRoll: 1 | 2 | 3 | 4 | 5 | 6; diceRoll = 4; // OK diceRoll = 6; // OK // diceRoll = 7; // Error: Type '7' is not assignable to type '1 | 2 | 3 | 4 | 5 | 6'
In the example above, the direction variable is limited to four possible string values: "left", "right", "up", or "down". Any attempt to assign a different string will result in a type error. Similarly, the diceRoll variable can only be one of the numbers from 1 to 6, matching the faces of a standard die. Literal types are especially useful for function parameters, configuration options, or any situation where only a specific set of values makes sense. By using literal types, you make your code safer, clearer, and more predictable.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione
Fantastico!
Completion tasso migliorato a 8.33
Literal Types
Scorri per mostrare il menu
Literal types in TypeScript allow you to specify that a variable can only have one or more exact values, rather than any value of a broader type like string or number. This restriction helps prevent errors by ensuring that only expected values are used in your code.
1234567891011// String literal type let direction: "left" | "right" | "up" | "down"; direction = "left"; // OK direction = "up"; // OK // direction = "forward"; // Error: Type '"forward"' is not assignable to type '"left" | "right" | "up" | "down"' // Number literal type let diceRoll: 1 | 2 | 3 | 4 | 5 | 6; diceRoll = 4; // OK diceRoll = 6; // OK // diceRoll = 7; // Error: Type '7' is not assignable to type '1 | 2 | 3 | 4 | 5 | 6'
In the example above, the direction variable is limited to four possible string values: "left", "right", "up", or "down". Any attempt to assign a different string will result in a type error. Similarly, the diceRoll variable can only be one of the numbers from 1 to 6, matching the faces of a standard die. Literal types are especially useful for function parameters, configuration options, or any situation where only a specific set of values makes sense. By using literal types, you make your code safer, clearer, and more predictable.
Grazie per i tuoi commenti!