TypeScript
/Intermediate
Literal Types
Definition
A Literal Type is a type that represents one exact, specific value. It is usually combined with Union Types to create a strict set of allowed values.
Explain Like I'm New
Instead of typing a variable as `string` (which means ANY word in the dictionary), a Literal Type means the variable must be exactly the word 'SUCCESS' or exactly the word 'ERROR'. Nothing else is allowed.
Real World Example
Typing a button component in React: `type ButtonVariant = 'primary' | 'secondary' | 'danger'`. If a developer passes `variant='blue'`, TS throws a compile error.
Common Use Cases
- •Strict UI component props
- •Redux Action Types
- •Enforcing specific configuration options
Interactive Example
Loading Code Playground...
Interview Questions
basic
- Can literal types be numbers or just strings?
intermediate
- Why does `const` automatically create a literal type?
advanced
- What is `as const`?