0
0
Typescriptprogramming~3 mins

Why Literal types and value narrowing in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your program could instantly know exactly what value it's dealing with, avoiding hidden bugs?

The Scenario

Imagine you have a program that accepts user commands like 'start', 'stop', or 'pause'. Without special checks, you might accidentally allow typos or unexpected values, causing bugs or crashes.

The Problem

Manually checking every possible string or value is slow and error-prone. You might forget a case or mistype a check, leading to unexpected behavior that's hard to find and fix.

The Solution

Literal types let you specify exact allowed values, and value narrowing helps the program understand which exact value it's working with. This prevents mistakes and makes your code safer and clearer.

Before vs After
Before
function handleCommand(cmd: string) {
  if (cmd === 'start' || cmd === 'stop' || cmd === 'pause') {
    // do something
  }
}
After
type Command = 'start' | 'stop' | 'pause';
function handleCommand(cmd: Command) {
  if (cmd === 'start') {
    // do start
  } else if (cmd === 'stop') {
    // do stop
  } else if (cmd === 'pause') {
    // do pause
  }
}
What It Enables

You can write code that knows exactly what values are allowed and safely handle each case without guesswork or errors.

Real Life Example

Think of a traffic light system where the light can only be 'red', 'yellow', or 'green'. Literal types ensure you never accidentally use an invalid color, keeping the system reliable.

Key Takeaways

Literal types specify exact allowed values.

Value narrowing helps the program understand which value it has.

This combination makes code safer and easier to maintain.