Search code examples
angulartypescriptenumerable

Convert enum structure value:key to key:value in TypeScript


I'm trying convert a enum structur from [key:value] with value as string to [value:key] structure with this code.

my error is

Element implicitly has an 'any' type because expression of type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | ... 31 more ... | "trimEnd"' can't be used to index type 'typeof Country'.
  No index signature with a parameter of type 'number' was found on type 'typeof Country'

key as keyof Country

enumeral

export enum Country {
    UnitedStates = 'US',
    Afghanistan = 'AF',
    AlandIslands = 'AX',
    }

code

 public countries = Object.keys(Country)
  .slice(Object.keys(Country).length / 2)
  .map(key => ({
    label: key,
    key: Country[key as keyof Country],
  }));

when value of enum is int this code works.


Solution

  • The issue is that you cast to the wrong type

    Here is a typescript playground example

    keyof Country includes all keys of the Country enum object - just hoover overt TKeys in the example to see the list

    What you actually want is: Country[key as keyof typeof Country]
    keyof typeof Country is the type of all enum keys: "UnitedStates" | "Afghanistan" | "AlandIslands"
    Hoover over TEnumKeys in the example.

    To understand the difference, check this question: What does “keyof typeof” mean in TypeScript?