如何在打字稿中迭代字符串文字类型

Fra*_*nke 6 enums typescript

如何在打字稿中迭代字符串文字类型?

例如我定义这种类型

type Name = "Bill Gates" | "Steve Jobs" | "Linus Torvalds";
Run Code Online (Sandbox Code Playgroud)

我想这样迭代

for (let name of Name) {
    console.log("Possible name: " + name);
}
Run Code Online (Sandbox Code Playgroud)

还是在打字稿中根本不可能?

Pau*_*son 34

您可以定义一个数组文字,而不是按照 OP 请求迭代(联合)字符串文字类型,如果标记,as const则条目的类型将是字符串文字类型的联合。

从 typescript 3.4 开始,您可以在文字表达式上定义 const 断言来标记: - 该表达式中的文字类型不应该被扩展(例如,不要从“hello”到字符串) - 数组文字变成只读元组

例如:

const names = ["Bill Gates", "Steve Jobs", "Linus Torvalds"] as const;
type Names = typeof names[number];
Run Code Online (Sandbox Code Playgroud)

它可以在运行时使用并检查类型,例如:

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];
Run Code Online (Sandbox Code Playgroud)

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

  • 如果对数组进行切片,它将成为联合类型的数组:`const n = [...names];`,您可以从中获取`typeof`条目:`type Names = typeof n[0]`因此语法`typeof name[number]` 似乎是上述内容的简写语法。我昨天在 https://dev.to/andreasbergqvist/typescript-get-types-from-data-using-typeof-4b9c 上发现了语法 `typeof name[number]` (2认同)

Aro*_*ron 11

由于 TypeScript 只是一个编译器,因此在运行时不存在任何类型信息。这意味着不幸的是你不能遍历一个类型。

根据您尝试执行的操作,您可以使用枚举来存储名称的索引,然后您可以在数组中检索这些索引。


Fra*_*nke 5

从 typescript 2.4 开始,可以使用字符串类型的枚举。这些枚举可以很容易地迭代:

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