Loop Through TypeScript Union Type

Here's a method to loop through the values in a union of literals in TypeScript.

Union Type

A Union type in TypeScript creates an "OR" relationship between other types. Here is a general union type:

type AlphaNumeric = string | number

These are two general types. We can't loop through these, because there are no values. But we can create a union of literal types, such as:

type Sizes = 'small' | 'medium' | 'large'

Define the Iterable

We want the union type. We want to loop. But as far as I can tell, looping requires code. We need an iterable, like an array. We can't loop through the type per se.

So let's first create the array in code, then derive the type from it:

const sizes = ['small', 'medium', 'large'] as const
type Size = typeof sizes[number]

That's it.

as const keeps the type as narrow as possible -- these listed literals, instead of, say, string[]. But I haven't found it strictly required.

typeof creates a type from code.

[number] indexing should be written exactly as demonstrated. number is a keyword in TypeScript and is meant here to mean "index of" generally.

Code the Loop

With the iterable, now we can loop in many ways, as we usually would:

sizes.map((size: Size) => console.log('size: ', size))