k0pernikus k0pernikus - 1 year ago 180
TypeScript Question

How to iterate over a custom type in typescript?

I have defined a custom type in typescript:

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

Now I want to iterate over each possible
without having to create an array of
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) => {

Is there a way to achieve that with typescript?

Answer Source

No, you can't do that, as pure type information like that doesn't exist at runtime.

It's hypothetically plausible to do the other way (define a normal list of strings, and then derive the 'au'|'br'|'de' type from that), but I don't think the TypeScript compiler (either 2.0 or 2.1) will currently infer that for you - as far as I know the type of markets will always be string[] normally.

The right answer to this is to use enums. They define a type with each of their values, and it's possible to get a list of all their string values: How to programmatically enumerate an enum type in Typescript 0.9.5?.

The one downside to enums is that their runtime representation is different (under the hood they're actually numbers, not strings). Your code can still treat them as nice readable values though, it's just you'll have to translate them to strings if do you ever you need them as string names at runtime. That's easy though: given enum MarketEnum and a value myEnumValue, MarketEnum[myEnumValue] is the value's name as a string).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download