How can I iterate a string literal type in typescript?
For example i define this type
type Name = "Bill Gates" | "Steve Jobs" | "Linus Torvalds";
I want to iterate like this
for (let name of Name) { console.log("Possible name: " + name); }
Or is this simply not possible in typescript?
No, you can't do that, as pure type information like that doesn't exist at runtime.
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.
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
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.
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