iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

TS Literal Types

A literal type is a type with exactly one possible value. Combined with unions, they're the foundation of safe, expressive APIs.

The three flavours

TS
let s: 'hello' = 'hello';   // string literal
let n: 42       = 42;        // numeric literal
let b: true     = true;      // boolean literal

Where they're useful — union of literals

TS
type Direction = 'up' | 'down' | 'left' | 'right';
type Diff = -1 | 0 | 1;
type Result = 'ok' | 'error';

Almost every "enum-shaped" thing can be modelled this way — simpler and tree-shakeable.

Inference and const

TS widens literals to their general type by default:

TS
let   s1 = 'hello';   // string  (widened)
const s2 = 'hello';   // 'hello' (literal)

const assertions

TS
const point = { x: 3, y: 4 };
// type: { x: number; y: number }

const point2 = { x: 3, y: 4 } as const;
// type: { readonly x: 3; readonly y: 4 }

satisfies — keep literals after a check

TS
type Theme = Record<string, '#' | 'rgb'>;

const theme = {
    primary:   '#04AA6D',
    secondary: 'rgb(28, 134, 252)',
} as const satisfies Record<string, string>;

// `theme.primary` keeps its literal type even after satisfying.
Tip: A great smell-test for literals: if a value comes from a config or an API and has a small known set, model it as a union of literals — IDEs autocomplete the choices and typos become compile errors.

Example

Example
type Direction = 'up' | 'down' | 'left' | 'right';
function move(d: Direction) { console.log('Moving', d); }

move('up');
// move('diagonal');   // ✗ error
Try it Yourself »

Exercise

Make ["paid", "pending"] a tuple of literals with…

const arr = ['paid', 'pending'] const;

Test yourself

Q1. "const x = 'hi'" has type…
Q2. "as const" makes object literals…
Q3. The "satisfies" operator helps you…

Discussion

Loading…