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