Home > Blockchain >  How to write a generic function to convert any enum value to its string representation?
How to write a generic function to convert any enum value to its string representation?

Time:07-14

My goal is this:

enum MyEnum {
    TheA,
    TheB,
    TheC
}

const strValue = enumToString(MyEnum, MyEnum.TheA)

strValue should be "TheA".

My closest attempt looks like this:

function enumToString<T extends { [name: number]: number|string }>(myenum: T, myenumvalue: number){
    return myenum[myenumvalue] as string;
}

The problem is, that this is still not type safe. One could use some totally different enum and the compiler would still accept that. For example:

 const strValue = enumToString(TotallyDifferentEnum, MyEnum.TheA)

Basically I need a generic constraint which ties both function parameters together. Something like this:

function enumToString<T extends { [name: number]: number|string }, K extends typeof T>(myenum: T, myenumvalue: K)

CodePudding user response:

You need to add a constraint to the 2nd parameter : T[keyof T] instead of number.

Also note that the key of your enum is of type string.

function enumToString<T extends { [name: string]: number | string }>(myenum: T, myenumvalue: T[keyof T]) {
  return myenum[myenumvalue];
}

Playground

CodePudding user response:

You can easily get the raw value of any enum string using For Kotlin

YourEnum.YourEnumValue.rawValue

In your case

const strValue = MyEnum.TheA.rawValue

Update: For TypeScript

MyEnum[MyEnum.TheA]
//this returns string 'TheA'
  • Related