TypeScript · Types that pay for themselves
What are literal types and when are they useful?
Short answer
Literal types describe exact values such as "open" or 42. Combined with unions they model finite states, and as const preserves literals instead of widening them.
A literal type is a type with exactly one value. String, number and boolean literals are the common cases. On their own they are narrow; combined in a union they describe a closed set of valid values, which is ideal for status fields, modes and configuration flags.
type Status = "idle" | "loading" | "success" | "error";
let status: Status = "idle";
status = "loading";
const config = {
mode: "dark",
retries: 3,
} as const;Why literals matter
- They reject typos such as "succes" at compile time
- They make discriminated unions and exhaustive checks possible
- They keep configuration objects precise when marked as const
- They can be derived from existing values with typeof
Without as const, object properties are widened to string and number because the object is mutable. The assertion keeps the literal types and makes the object deeply readonly at the type level. That is useful for constants, route tables and action names.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why does an object property widen to string without as const?
- 2How do literal types enable discriminated unions?
- 3What is the difference between a literal type and an enum?
- 4Does as const make the object immutable at runtime?
Say it in the interview
Literal types represent exact values, and unions of them model finite states like idle, loading or error. With as const I can keep an object's properties as literals instead of widening them to string or number. That gives me precise types from configuration objects without writing a separate type. I use literal unions for app state and reserve enums for cases that need a runtime object.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live TypeScript mock interview and get scored feedback on depth, clarity and confidence.