JoyEnum.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { Constructor } from '@polkadot/types/types';
  2. import { Enum } from '@polkadot/types/codec';
  3. import { EnumConstructor } from '@polkadot/types/codec/Enum';
  4. export interface ExtendedEnum<Types extends Record<string, Constructor>> extends Enum {
  5. isOfType: (type: keyof Types) => boolean;
  6. asType<TypeKey extends keyof Types>(type: TypeKey): InstanceType<Types[TypeKey]>;
  7. };
  8. export interface ExtendedEnumConstructor<Types extends Record<string, Constructor>> extends EnumConstructor<ExtendedEnum<Types>> {
  9. create<TypeKey extends keyof Types>(typeKey: TypeKey, value: InstanceType<Types[TypeKey]>): ExtendedEnum<Types>;
  10. }
  11. // Helper for creating extended Enum type with TS-compatible isOfType and asType helpers
  12. export function JoyEnum<Types extends Record<string, Constructor>>(types: Types): ExtendedEnumConstructor<Types>
  13. {
  14. // Unique values check
  15. if (Object.values(types).some((val, i) => Object.values(types).indexOf(val, i + 1) !== -1)) {
  16. throw new Error('Values passed to JoyEnum are not unique. Create an individual class for each value.');
  17. }
  18. return class JoyEnumObject extends Enum {
  19. public static create<TypeKey extends keyof Types>(typeKey: TypeKey, value: InstanceType<Types[TypeKey]>) {
  20. return new JoyEnumObject({ [typeKey]: value });
  21. }
  22. constructor(value?: any, index?: number) {
  23. super(types, value, index);
  24. }
  25. public isOfType(typeKey: keyof Types) {
  26. return this.value instanceof types[typeKey];
  27. }
  28. public asType<TypeKey extends keyof Types>(typeKey: TypeKey) {
  29. if (!(this.value instanceof types[typeKey])) {
  30. throw new Error(`Enum.asType(${typeKey}) - value is not of type ${typeKey}`);
  31. }
  32. return this.value as InstanceType<Types[TypeKey]>;
  33. }
  34. }
  35. }