Posts > TS Basic: Literal Types
August 20, 2023
function printText(s: string, alignment: 'left' | 'right' | 'center'){
//rest of code
}
printText('Hello', 'right')
👌This feature provides more PRECISE TYPE CHECKING and helps enforce STRICTER constraints on the values that can be assigned.
let userStatus : 'sucess' | 'error'
userStatus = 'success' // ok
userStatus = 'failure' // error: Type '"failure"' is not assignable to type '"success" | "error"'.
let diceRoll: 1 | 2 | 3 | 4 | 5 | 6;
diceRoll = 5; // ok
diceRoll = 8; // error: Type '8' is not assignable to type '1 | 2 | 3 | 4 | 5 | 6'.
type Size = 'small' | 'medium' | 'large';
type Color = 'red' | 'green' | 'blue';
function createBox(size: Size, color: Color){
//rest of code
}
createBox('small','red'); //valid
createBox('extra-small', 'yellow'); // invalid
enum Direction {
Up = "Up",
Down = "Down",
Left = "Left",
Right = "Right",
}
let currentDirection: Direction = Direction.Up; // ok
let currentDirection: Direction = Direction.West; // Property 'West' does not exist on type 'typeof Direction'.
👌Using literal types, you can define and enforce specific values, making your code more EXPLICIT and catching potential errors at compile-time.