0

I have the following typescript enum:

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

Further I have a GUI where i set my initial texture to show:

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

let settings = new DefaultSettings();

So when i change the value in my GUI, selecting "Colors" I don't want to write my callback for every single entry in the enum. eg:

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;
}

How can I set the Texture Enum object into the settings.texture attribute? E.G.:

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

or

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

Thank you for any help!

1 Answer 1

2

If you are sure that the type of selcted.value will always be the enum value, you can do something like this:

settings.texture = selcted.value as Textures

Also, I would also recommend to:

  • rename Textures to Texture as naming convention recommend using singular names for enum [source]
  • change your enum key to ALL_CAPS or Capital format
  • check with === instead of == [eslint eqeqeq]
  • rename selcted to selected
Sign up to request clarification or add additional context in comments.

1 Comment

If you aren't sure that the value will always be a texture, you can check it against the values of the enum: const isTexture = (value: string): value is Textures => (Object.values(Textures) as string[]).includes(value);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.