TypeScript Course
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`?

Flash Cards

Question

Can they be numbers?

Click to reveal answer
Answer

Yes! They can be strings, numbers, or booleans. e.g., `type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;`.

Question

What is as const?

Click to reveal answer
Answer

A 'Const Assertion'. If you define an object `const req = { url: '/api', method: 'GET' }`, TS types `method` as a generic `string`. If you add `as const` at the end, TS locks it down so `method` is strictly typed as the literal `'GET'`.