0

I want to map all enum values to the SelectItem array interface.

selectItem.ts

 export interface SelectItem {
        label?: string;
        value: any;
    }

gender.ts

export enum Gender{
  Description("MaleDescriptionExample")  //?????????
  Male = 1,
  Description("FemaleDescriptionExample")//?????????
  Female = 2
}

I want below for example. I wrote like C#. But I want it in typescript. How can I do this?

  var myList= selectItem[] ;
  this.myList=Gender.map(p=>  //?????????
    label= p.Description,
    value= (int)(p.value)
  );
4
  • 1
    What are you trying to accomplish with Description("...")? I don't think that's valid typescript Commented Sep 20, 2018 at 12:06
  • What is the goal here? You don't map over interfaces, even if it was possible. An interface is just a contract for an object to follow. You only have one interface, no more. Commented Sep 20, 2018 at 12:08
  • My main purpose is binding combobox from enum. But enum names aren't with space. And i can't show it at combobox (forexample: "PrimarySchool" but i want "Primary School"). So i need description like C#. Can i do in typescript? Or another way? @ShamPooSham Commented Sep 20, 2018 at 12:12
  • Ok. I can change as class. No problem. My main purpose is binding all enum values to array. But i need Description for enum. @theblindprophet Commented Sep 20, 2018 at 12:14

1 Answer 1

5

You can't add decorators to enums as you would add attributes to C# enums. We can however create a type with the same keys as the enum that will force us to specify all the keys of the enum with their string description.

With that object, we then just need to get the keys of the enum, and lookup the values in the enum and the description in our extra object.

export enum Gender {
  Male = 1,
  Female = 2
}

// We will geta an error if we have missing/ extra or misspelled keys
let descriptions: { [P in keyof typeof Gender]: string } = {
  Female: "FemaleDescriptionExample",
  Male: "MaleDescriptionExample"
}
export interface SelectItem {
  label?: string;
  value: any;
}
var myList: SelectItem[] = (Object.keys(Gender) as Array<keyof typeof Gender>)
  .filter(p => typeof Gender[p] === "number") // The enum contains both the lookup and the reverse lookup, we only need name->value so we take only the number keys
  .map(p => ({
    label: descriptions[p],
    value: Gender[p]
  }));

console.log(myList);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @TitianCernicova-Dragomir. This is what i looking for. I will try and write whether work or not
Yes i tried and it worked. Thanks again @TitianCernicova-Dragomir

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.