Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate over a custom literal type in TypeScript?

I have defined a custom literal type in TypeScript:

export type Market = 'au'|'br'|'de'; 

Now I want to iterate over each possible Market without having to create an array of Market[] in the first place as it feels redundant and I may forget to add one option:

const markets: Market[] = ['au', 'br', 'de']; markets.forEach((market: Market) => {     console.log(market); }); 

Is there a way to achieve that with TypeScript?

like image 455
k0pernikus Avatar asked Nov 29 '16 10:11

k0pernikus


People also ask

How do I loop through a string in TypeScript?

To iterate over a string with index: Use the spread syntax (...) to unpack the string into an array. Use the forEach() method to iterate over the array. The second parameter the forEach() method takes is the index of the current element.

How do I iterate through a map in TypeScript?

Use the forEach() method to iterate over a Map in TypeScript. The forEach method takes a function that gets invoked for each key/value pair in the Map . The function gets passed the value, key and the Map object on each iteration.

What is literal type in TypeScript?

The string literal type allows you to specify a set of possible string values for a variable, only those string values can be assigned to a variable. TypeScript throws a compile-time error if one tries to assign a value to the variable that isn't defined by the string literal type.


Video Answer


1 Answers

For those of you visiting this question using TypeScript >= 3.4, I believe the best practice is now to create a constant array of strings and then use the type of operator.

Example:

export const markets = ['au', 'br', 'de'] as const; export type Market = typeof markets[number];  markets.forEach((market: Market) => {     console.log(market); }); 
like image 86
keithhackbarth Avatar answered Sep 19 '22 14:09

keithhackbarth