0
0
Typescriptprogramming~5 mins

Literal types and value narrowing in Typescript

Choose your learning style9 modes available
Introduction

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.

When you want a variable to only hold a few specific values, like 'yes' or 'no'.
When you want to check a variable's value and have TypeScript know exactly which case it is.
When you want safer code by preventing unexpected values.
When writing functions that behave differently based on exact input values.
Syntax
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.

Examples
This variable can only be 'yes' or 'no'. Assigning 'maybe' causes an error.
Typescript
let answer: 'yes' | 'no';
answer = 'yes'; // OK
answer = 'maybe'; // Error: not allowed
Inside the if, TypeScript knows dir is exactly 'left'. In else, it knows dir is 'right'.
Typescript
function printDirection(dir: 'left' | 'right') {
  if (dir === 'left') {
    console.log('Going left');
  } else {
    console.log('Going right');
  }
}
Using as const makes the variable a literal type. The switch narrows the value to each case.
Typescript
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);
Sample Program

This program uses a literal type Direction to allow only four directions. The function move checks the exact value and prints a message accordingly.

Typescript
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');
OutputSuccess
Important Notes

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.

Summary

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.