【问题标题】:How to store enum object in variable Typescript如何将枚举对象存储在变量Typescript中
【发布时间】:2021-01-15 01:31:01
【问题描述】:

我有以下打字稿枚举:

export enum Textures { 
    earth = "Earth", 
    colors = "Colors", 
    disturb = "Disturb",
    ...,
    many = "More"
}

此外,我还有一个 GUI,可以在其中设置要显示的初始纹理:

export class DefaultSettings {
  texture: Textures = Textures.earth;
  //more Settings
}

let settings = new DefaultSettings();

因此,当我更改 GUI 中的值时,选择“颜色”我不想为枚举中的每个条目编写回调。例如:

if(selcted.value == "Colors"){
  settings.texture = Textures.colors;
}
if(selcted.value == "Disturb"){
  settings.texture = Textures.disturb;
}
if(selcted.value == "Earth"){
  settings.texture = Textures.earth;
}

...

if(selcted.value == "More"){
  settings.texture = Textures.many;
}

如何将Texture Enum object 设置为settings.texture 属性?例如:

settings.texture = Textures.X // This saves the string, but I want the object itself

或

settings.texture = Textures[X] // wrong since it puts 'string' instead of 'Textures'

感谢您的帮助!

【问题讨论】:

    标签: typescript enums


    【解决方案1】:

    如果你确定selcted.value 的类型总是枚举值,你可以这样做:

    settings.texture = selcted.value as Textures
    

    另外,我还建议:

    • 将Textures 重命名为Texture,因为命名约定建议为enum 使用单数名称[source]
    • 将您的枚举键更改为ALL_CAPS 或Capital 格式
    • 检查=== 而不是== [eslint eqeqeq]
    • 将selcted 重命名为selected

    【讨论】:

    • 如果您不确定该值是否始终是纹理,您可以对照枚举值进行检查:const isTexture = (value: string): value is Textures => (Object.values(Textures) as string[]).includes(value);
    猜你喜欢
    • 2017-01-28
    • 2014-09-20
    • 2019-05-09
    • 2022-01-24
    • 2014-09-09
    • 1970-01-01
    • 2020-04-04
    • 2017-08-23
    • 2020-03-14
    相关资源
    最近更新 更多