简体   繁体   中英

How to define the type "any string enum" in typescript?

I had to change per request a lot of number based enum to string enums and now I need to make an enum converter for the already stored enum values in a storage API, so I had:

enum MyEnum {
  FirstValue,
  SecondValue
}

which now is

enum MyEnum {
  FirstValue = "FirstValue",
  SecondValue = "SecondValue"
}

and recover some object stored like

myObject = {
  myEnum = 0
}

I have to recover that and store it again as:

myObject = {
  myEnum = 'FirstValue'
}

As for now I already have the logic for it but I have problems with my function definition, I do not know how to define an "any string enum" without adding a index signature to all my enums.

I tried to use an interface with an index signature

interface EnumToFix {
  [key: string]: string;
}

but if I give it to my function I get as error:

Argument of type 'typeof MyEnum' is not assignable to parameter of type 'EnumToFix'. Index signature is missing in type 'typeof MyEnum'.

my current function definition is

private async fixGeneral<T>(storageKey: StorageKeyItems, enumToFix: EnumToFix, objectKeyToFix: keyof T): Promise<void>

If I ignore the error with @ts-ignore it works as expected.

Sometimes it is okay, to just cast an object to unknown and then in your target type, when you KNOW it better. But you would need to provide the logic inside your "fixGeneral" function, to convert myObject properly. So you could do something like this:

enum MyEnum {
    FirstValue = "FirstValue",
    SecondValue = "SecondValue"
  }

let myObject: { myEnum: string | number } = { myEnum: 0 };

for (const propName of Object.keys(myObject)) 
    if (typeof myObject[propName] === "number") 
        myObject[propName] = MyEnum[myObject[propName]];

let myObjectTyped = myObject as unknown as { myEnum: MyEnum };

When you meant something different, I would ask you for more details/code. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM