将字符串数组转换为TypeScript中的枚举类型

11 浏览
0 Comments

将字符串数组转换为TypeScript中的枚举类型

我正在玩一下Typescript。\n假设我有一个这样的对象:\n

let colors = {
    RED: "r",
    GREEN: "g",
    BLUE: "b"
}

\n现在我想将其转换为枚举类型:\n

enum Colors = {
    RED = "r",
    GREEN = "g",
    BLUE = "b"
}

\n更新:\n我希望生成的typings可以包含colors对象的任何新键,如果我向colors对象添加另一个键,它应该包含在typings中。\n如果我执行以下操作:\n

colors['YELLOW'] = "y"

\n那么生成的typings应该是:\n

declare enum colors {
    RED = "r",
    GREEN = "g",
    BLUE = "b",
    YELLOW = "y"
}

\n然而,生成的typings是:\n

declare const colors {
     [x: string]: string        
}

\n我该如何实现这一点?

0
0 Comments

在Typescript中,我们可以使用枚举(Enums)来定义一组命名的常量。使用枚举可以更容易地记录意图或创建一组不同的情况。Typescript提供了基于数字和基于字符串的枚举。

在Typescript 2.4之前,Typescript只支持基于数字的枚举。在这种情况下,只需将字符串文字强制转换为any,然后进行赋值。但在2.4版本及以上,不再需要使用any进行转换。

以下是一个使用字符串的枚举的例子:

enum Colors {
    RED = <any>"R",
    GREEN = <any>"G",
    BLUE = <any>"B",
}

如果要将字符串数组转换为枚举类型,可以使用下面的实用函数:

function strEnum<T extends string>(o: Array<T>): {[K in T]: K} {
  return o.reduce((res, key) => {
    res[key] = key;
    return res;
  }, Object.create(null));
}
let dynamicArrayJSON = [ 'RED', 'BLUE', 'GREEN' ]
const Colors = strEnum( dynamicArrayJSON )

上述代码中的strEnum函数可以帮助将字符串列表转换为K:V类型的对象。

这个问题的解决方法可以参考以下链接:

- How to create enum like type in TypeScript?

- Create an enum with string values in Typescript

- When to use a semicolon in TypeScript?

- Typescript enum from JSON string

通过使用上述的实用函数,我们可以将静态或动态的JSON对象转换为枚举类型,从而方便地使用。

0