Home > Software engineering >  Type for Object.keys(someEnum) in typescript
Type for Object.keys(someEnum) in typescript

Time:05-18

In my problem, I am extracting keys of an enum using Object.keys as follows:

const enum Foo {
    FOO = 'foo',
    BAR = 'bar'
}

const keys = Object.keys(Foo)

When I then try to use the same keys to point at values from Foo enum, I am getting the following error:

Foo[keys[0]] // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof Foo'.

What kind of type should I cast keys to in order for the above to work?

CodePudding user response:

const enum is not compiled to an object. in fact , if you don't use Foo.BAR it is getting erased. Please see TS playground

const enum Foo {
    FOO = 'foo',
    BAR = 'bar'
}

compiles to "use strict", in other words to empty file.

enter image description here

If you want it to be compiled, please use dot notation:

const enum Foo {
    FOO = 'foo',
    BAR = 'bar'
}

Foo.BAR

compiles to:

"use strict";
"bar" /* BAR */;

enter image description here

However, if you even get rid of const, you will not get rid of error, because enums are staticaly known values. You are not allowed to use computed keys as a getter.

Hence, you are allowed to use either Foo.BAR or Foo['BAR']

CodePudding user response:

Here is a playground example which casts the Object.keys to the value of the enum keys, and allows indexing access.

If you see the logs you'll see it logs foo and bar.

enum Foo {
    FOO = 'foo',
    BAR = 'bar'
}

const keys = Object.keys(Foo) as (keyof typeof Foo)[]

keys.forEach((a) => {
    console.log(a)
})

enter image description here Playground link

  • Related