1

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?

1
  • Your example code gives an error unrelated to your question; there is no object named Foo at runtime. Please provide a minimal reproducible example that clearly demonstrates the issue you are facing. Ideally someone could paste the code into a standalone IDE like The TypeScript Playground (link here!) and immediately get to work solving the problem without first needing to re-create it. Commented May 17, 2022 at 14:08

2 Answers 2

2

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']

Sign up to request clarification or add additional context in comments.

1 Comment

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.