Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate a string literal type in typescript

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?

like image 982
Franziskus Karsunke Avatar asked Mar 28 '17 10:03

Franziskus Karsunke


People also ask

Can you iterate over a type in TypeScript?

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

What is literal type in TypeScript?

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.


2 Answers

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

like image 117
Paul Thompson Avatar answered Sep 20 '22 21:09

Paul Thompson


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.

like image 28
Aron Avatar answered Sep 21 '22 21:09

Aron