我偶然发现了一个问题,那就是我需要迭代泛型枚举类型。 我正在尝试获取枚举类型的值。
for 循环参数中 GetPaths 函数中的 Typescript 错误:
"'T' 仅指一个类型,但在此处用作值"
export enum ERoutingPaths {
Home = "/",
About = "/About"
}
export enum EGamePaths {
Snake = "/Snake",
Maze = "/Maze",
}
function GetPaths<T extends ERoutingPaths | EGamePaths>():any {
let result = "";
for (let item in Object.values(T)) {
result += item + "|";
}
return result;
}
如果我还有其他枚举类型,我如何创建一个允许我迭代通用枚举类型的函数?
答案 0 :(得分:1)
具有字符串值的枚举是具有严格键值类型的旧式纯 JavaScript 对象。您可以使用 Record<string, string>
类型。
function GetPaths(value: Record<string, string>): string {
let result = "";
for (let item in value) {
result += value[item] + "|";
}
return result;
}
如果您只想在此处允许一组严格的类型,您可以使用泛型并使用:T extends typeof ERoutingPaths | typeof EGamePaths
。注意一个词 typeof
- 我们必须从枚举中提取一个类型。还需要进行一项更改。
for (let item in value) {
result += value[item as keyof T] + "|";
}
TypeScript 将 item
类型扩展为 string
- 编译器不允许使用带有枚举的字符串,因此我将其转换回 keyof T
。