How to iterate a string literal type in typescript

Since TypeScript is just a compiler, none of the typing information is present at runtime. This means that unfortunately you cannot iterate through a type.

Depending on what you're trying to do it could be possible for you to use enums to store indices of names that you can then retrieve in an array.


AFAIK there is no way to "lift" a string union (type) to runtime JS (value).

The closest solution I found was to use enum: example / related issue.


Since typescript 2.4 it is possible to use string typed enums. These enums can easily be iterated:

https://blogs.msdn.microsoft.com/typescript/2017/06/27/announcing-typescript-2-4/


Rather than iterating a (union of) string literal types as the OP requested, you can instead define an array literal and if marked as const then the entries' type will be a union of string literal types.

Since typescript 3.4 you can define const assertions on literal expressions to mark that: - no literal types in that expression should be widened (e.g. no going from "hello" to string) - array literals become readonly tuples

For example:

const names = ["Bill Gates", "Steve Jobs", "Linus Torvalds"] as const;
type Names = typeof names[number];

It can be used at runtime and with types checked, for example:

const companies = {
    "Bill Gates" : "Microsoft",
    "Steve Jobs" : "Apple",
    "Linus Torvalds" : "Linux",
} as const;

for(const n of names) {
    console.log(n, companies[n]);
}
const bg : Names = 'Bill Gates';
const ms = companies[bg];

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions

https://mariusschulz.com/blog/const-assertions-in-literal-expressions-in-typescript

https://microsoft.github.io/TypeScript-New-Handbook/chapters/types-from-extraction/#indexed-access-types