Cocos Creator doesn’t handle string-typed enums in its properties, and since I needed to use such an enum (coming from an external library, which I couldn’t modify) to create a dropdown in the inspector, I searched for a solution. After searching in this forum, I couldn’t find one, so I rolled up my sleeves.
It’s possible to generate a copy of the enum by removing the string assignments:
typescript
export function createEnumCopyWithoutString(
originalEnum: Record<string, string>
): Record<string, number> & Record<number, string> {
const enumCopy: Record<string, number> & Record<number, string> = {};
let index = 0;
for (const key in originalEnum) {
if (Object.prototype.hasOwnProperty.call(originalEnum, key)) {
enumCopy[key] = index;
enumCopy[index] = key;
index++;
}
}
return enumCopy;
}
If we have an enum:
typescript
enum Example {
a = 'aaaaa',
b = 'bbbbb',
c = 'ccccc'
}
and we want to use it in a @property
, we can do:
typescript
const ExampleWithoutString = createEnumCopyWithoutString(Example);
@ccclass('TestEnum')
export class TestEnum {
@property({ type: Enum(ExampleWithoutString) })
public readonly exampleEnum = ExampleWithoutString.a;
}
If you need to use the string value, you can simply use Example[ExampleWithoutString[this.exampleEnum]]
, which will return 'aaaaa'
if this.exampleEnum === ExampleWithoutString.a.
Hope this helps someone!