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?
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.
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.
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.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With