Overview - Literal types and value narrowing
What is it?
Literal types in TypeScript are specific values like exact strings or numbers that a variable can hold. Value narrowing means TypeScript can figure out a variable's exact value or smaller set of possible values during code checks. This helps catch mistakes early by knowing more precisely what values variables have. It makes your code safer and easier to understand.
Why it matters
Without literal types and value narrowing, TypeScript would treat variables as broad categories like 'any string' or 'any number'. This can hide bugs where a variable has an unexpected value. Literal types let TypeScript know exact values, so it can warn you if you use a wrong value. This makes programs more reliable and easier to maintain, saving time and frustration.
Where it fits
Before learning this, you should understand basic TypeScript types like string, number, and boolean. After this, you can learn about union types, type guards, and advanced type inference. Literal types and narrowing are foundational for writing precise and safe TypeScript code.