Objects and unions

Restrict values with literal unions

Model a small closed set of allowed strings or numbers instead of accepting every value of the primitive type.

A literal type is a type with exactly one value. 'loading' is a type whose only member is the string 'loading'. On its own that is not very useful. Combined in a union, it becomes one of the most practical tools in TypeScript.

A literal union makes invalid states harder to represent:

type Status = 'idle' | 'loading' | 'success' | 'error'

Use it at the boundary:

function setStatus(status: Status) {}

setStatus('loading')
setStatus('loadng')

The misspelled value fails during checking:

Argument of type '"loadng"' is not assignable to parameter of type 'Status'.

Callers also get autocomplete for the allowed states. Type the opening quote and the editor lists all four values.

A plain string would accept every spelling, even though the application understands only four values. The union makes that closed set visible, and it turns “which statuses exist?” from a documentation question into something the compiler answers.

Watch for widening

Literal types can widen when values move through mutable objects:

const request = { status: 'loading' }

Because request.status can be reassigned, TypeScript usually infers string. Pass request.status to setStatus() and you get:

Argument of type 'string' is not assignable to parameter of type 'Status'.

Annotate the object or use an appropriate const assertion when you need the literal preserved:

const request: { status: Status } = { status: 'loading' }
const fixed = { status: 'loading' } as const

The annotation keeps the property assignable to other Status values. The as const version locks it to exactly 'loading' and makes it readonly. Choose based on whether the object should change.

The runtime is still plain strings

The runtime values remain ordinary strings. Nothing at runtime prevents a network response from carrying 'cancelled' or garbage. Validate outside data before treating it as Status; the union is a compile-time contract between parts of your own code.

Exercise: add a 'cancelled' state and follow the compiler errors to every place that needs a decision.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →