TypeScriptBasic types

Literal types

Types that allow only specific values, e.g. "easy" | "hard".

On this page

Example

#
TypeScript
type Theme = 'light' | 'dark' | 'system'

function applyTheme(theme: Theme): string {
  return theme === 'system' ? 'Theme matches the system' : `Theme: ${theme}`
}

console.log(applyTheme('dark'))
console.log(applyTheme('system'))
Result
Theme: dark
Theme matches the system

Definition and usage

#

A literal type is a type whose only allowed value is one specific literal: "easy", 42, or true. On its own it’s not very useful, but combined into a union it creates a precise list of allowed values.

The declaration type Theme = "light" | "dark" | "system" means a variable typed Theme only accepts those three strings. A typo like "drak" gets caught right away, and the editor suggests the available options.

Variables declared with const automatically get a literal type. With let, TypeScript widens the type to string or number, because the value might change.

Syntax

#
Syntax
type Name = "value1" | "value2" | 3

More examples

#
A typo caught by the compiler
TypeScript
applyTheme('drak')
// Error: Argument of type '"drak"' is not assignable to parameter of type 'Theme'.
const vs let
TypeScript
const fixed = 'hard'
// type: "hard"
let changing = 'hard'
// type: string

Good practices

#
  • Literal unions are often a better choice than an enum: they’re lighter and read clearly in data.
  • To freeze literals in an object or array, use as const.

Related entries

#

Spotted a mistake or missing an example? Write to us.