如何在TypeScript中迭代字符串字面量类型

23 浏览
0 Comments

如何在TypeScript中迭代字符串字面量类型

如何在typescript中迭代字符串字面类型?

例如,我定义了这个类型

type Name = "Bill Gates" | "Steve Jobs" | "Linus Torvalds";

我想要像这样迭代

for (let name of Name) {
    console.log("Possible name: " + name);
}

或者在typescript中是否根本不可能?

admin 更改状态以发布 2023年5月24日
0
0 Comments

由于TypeScript仅仅是一个编译器,没有任何类型信息在运行时存在。这意味着,不幸的是,您无法迭代一个类型。

根据您要做什么,您可以使用枚举来存储名称的索引,然后在数组中检索它们。

0
0 Comments

与 OP 请求的遍历(联合)字符串字面类型不同,您可以定义一个数组字面量,如果标记为 as const,那么条目的类型将是字符串字面类型的联合。

自 TypeScript 3.4 以来,您可以对文本表达式定义常量断言来标记:
  - 该表达式中没有文字类型应该被扩大(例如,不应从“hello”转换为字符串)。
  - 数组字面量变为只读元组

例如:

const names = ["Bill Gates", "Steve Jobs", "Linus Torvalds"] as const;
type Names = typeof names[number];

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

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

0