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 Name = typeof names[number];
Iterating that at runtime:
for(const n of names) {
const val : Name = n;
console.log(val);
}
It can often be more useful to define it as an object, especially if there's value information to associate to the entries:
const companies = {
"Bill Gates" : "Microsoft",
"Steve Jobs" : "Apple",
"Linus Torvalds" : "Linux",
} as const;
type Person = keyof typeof companies;
type Company = typeof companies[Person];
for(const n of names) {
const p : Person = n;
const c : Company = companies[p];
console.log(p, c);
}
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://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html