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
// Defining a Union of Literal Types type Alignment = "left" | "center" | "right"; function setAlignment(align: Alignment) { // Do something... } setAlignment("left"); // Valid setAlignment("center"); // Valid // setAlignment("top"); // ERROR: Argument of type '"top"' is not assignable to parameter of type 'Alignment'. // Numeric Literals type StatusCodes = 200 | 404 | 500; // Const Assertion example const config = { method: "GET" // Inferred as 'string' normally } as const; // Now inferred exactly as the literal 'GET'
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`?