Iterating over a string literal type in typescript

- 2 mins

In typescript literal types are amazing, I personally love to limit certain fields from a form using string literals. Something like this:

type Company = 'google' | 'facebook' | 'apple';

But very often I want to iterate over the possible values of Company - imagine a Select button as an example.

For this case most answers would suggest that you use an enum type instead as it provides ways to iterate over it's items. That's a possible solution, but in this post I'd like to offer a different approach, one that resolves at compiler time and so that the type Company behaves like it was defined literally:

const companies = ['google', 'facebook', 'apple'] as const;
type Company = typeof companies[number];

Since typescript 3.4 a concept called const assertion was introduced to indicate to compiler that the value is constant and should be replaced at compilation. Now typescript knows all the possible values for companies, thus it can define a literal type from that value (because it's constant etc etc).

The second line is called indexed access types and we can define our type extracting it from an object or array item (more examples on the link).

At the end you should see that the type of Company is the same as it were if we'd defined it literally

type Company = 'google' | 'facebook' | 'apple';
// is the same as 
const companies = ['google', 'facebook', 'apple'] as const;
type Company = typeof companies[number];

And now you can iterate over Company accepted values using the const variable companies 😄

Vieira Neto

Vieira Neto

Another bivalve on the web

rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora