Literal types let you use exact values as types. Value narrowing helps TypeScript understand what exact value a variable holds, so it can catch mistakes early.
Literal types and value narrowing in Typescript
let direction: 'left' | 'right' | 'up' | 'down'; function move(dir: 'left' | 'right' | 'up' | 'down') { if (dir === 'left') { // do something } else if (dir === 'right') { // do something else } }
Literal types are written as exact values in quotes, like 'left' or 42.
Value narrowing happens when you check a variable's value with if or switch, so TypeScript knows the exact value inside that block.
let answer: 'yes' | 'no'; answer = 'yes'; // OK answer = 'maybe'; // Error: not allowed
function printDirection(dir: 'left' | 'right') { if (dir === 'left') { console.log('Going left'); } else { console.log('Going right'); } }
as const makes the variable a literal type. The switch narrows the value to each case.const status = 'success' as const; function handleStatus(s: 'success' | 'error') { switch (s) { case 'success': console.log('It worked!'); break; case 'error': console.log('There was an error.'); break; } } handleStatus(status);
This program uses a literal type Direction to allow only four directions. The function move checks the exact value and prints a message accordingly.
type Direction = 'north' | 'south' | 'east' | 'west'; function move(direction: Direction) { if (direction === 'north') { console.log('Moving up'); } else if (direction === 'south') { console.log('Moving down'); } else { console.log(`Moving ${direction}`); } } move('north'); move('west');
Literal types help catch errors early by limiting allowed values.
Value narrowing works well with if, else, and switch statements.
Use as const to make variables have literal types instead of general types.
Literal types let you specify exact allowed values for variables.
Value narrowing helps TypeScript understand which exact value a variable has after checks.
Together, they make your code safer and easier to understand.