What if your program could instantly know exactly what value it's dealing with, avoiding hidden bugs?
Why Literal types and value narrowing in Typescript? - Purpose & Use Cases
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.
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.
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.
function handleCommand(cmd: string) {
if (cmd === 'start' || cmd === 'stop' || cmd === 'pause') {
// do something
}
}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 } }
You can write code that knows exactly what values are allowed and safely handle each case without guesswork or errors.
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.
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.