TypeScript TS7015 error when accessing an enum using a string type parameter

If you’re using TypeScript 2.1+, you can change enumKey‘s type to keyof typeof State, like this:

function Emote(enumKey: keyof typeof State) {...}

or, if the function’s input is required to be a string, this:

var state : State = State[enumKey as keyof typeof State];

Explanation:

Because enumKey is an arbitrary string, TypeScript doesn’t know whether enumKey is the name of a member of State, so it generates an error. TypeScript 2.1 introduced the keyof operator which returns a union of the known, public property names of a type. Using keyof allows us to assert that the property is indeed in the target object.

However, when you create an enum, TypeScript actually produces both a type (which is typically a subtype of number) and a value (the enum object that you can reference in expressions). When you write keyof State, you’re actually going to get a union of the literal property names of number. To instead get the property names of the enum object, you can use keyof typeof State.

Sources:

https://github.com/Microsoft/TypeScript/issues/13775#issuecomment-276381229
https://www.typescriptlang.org/docs/handbook/enums.html#enums-at-compile-time

Leave a Comment