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

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

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'`.