【问题标题】:Converting String array to Enum in Typescript在 Typescript 中将字符串数组转换为枚举
【发布时间】:2018-07-07 02:27:11
【问题描述】:

我正在玩一些 Typescript。

假设我有一个像这样的object

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

现在我想把它转换成enum 类型

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

更新:

我想要为 colors 对象生成typings,这样 如果我向颜色对象添加另一个key,它应该包含在typings 中。

如果我这样做了

colors['YELLOW'] = "y"

那么生成的typings应该是

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

相反,生成的类型是

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

我怎样才能做到这一点?

【问题讨论】:

  • 你有什么用途?不要认为您可以基于对象字面量创建实际的枚举类型,但您可以创建一个非常模仿其行为的对象。
  • 你可以做相反的事情 - 将enum 转换为对象
  • @TitianCernicova-Dragomir 我已经用我真正想要实现的目标更新了问题
  • 我期望的是一个数组,而不是一个对象。您的问题标题与正文完全无关。这将是一个数组:["red", "blue", "green"],我希望它被转换成一个enum Color { red, blue, green }

标签: arrays typescript object types enums


【解决方案1】:

Enums « 枚举允许我们定义一组命名常量。使用枚举可以更轻松地记录意图,或创建一组不同的案例。 TypeScript 提供基于数字和基于字符串的枚举。

TypeScript 2.4+String enums - 在 TypeScript 2.4 之前,TypeScript 仅支持基于数字的枚举,在这种情况下,只需在分配之前将字符串文字转换为 any,然后使用 2.4+不再需要任何东西

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

Java 脚本 Standard Style

var Colors;
(function (Colors) {
    Colors["RED"] = "r";
    Colors["GREEN"] = "g";
    Colors["BLUE"] = "b";
})(Colors || (Colors = {}));

签入 TypeScript Fiddle fiddlesalad, typescriptlang


下面的实用函数从字符串列表中创建K:V 可能会对您有所帮助。

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 )

@see

【讨论】:

  • 我想把上面的object类型转换成enum类型。
  • 要转为枚举的静态json对象或动态json对象
  • 动态JSON object
  • 查看对您有帮助的实用功能!
猜你喜欢
  • 2019-03-10
  • 2021-04-11
  • 2013-06-27
  • 1970-01-01
  • 2017-07-07
  • 2014-09-27
  • 2020-10-30
  • 2012-11-30
相关资源
最近更新 更多