Reputation: 39374
When using TypeScript and strict
enabled I have the enum:
export enum Policy {
Admin,
Editor
}
Then on a class I have:
policy?: Policy;
setPolicy(policy: string) {
this.policy = Policy[policy];
}
I need to define the policy variable from a string.
When using strict
and try to compile I get the error:
Element implicitly has an 'any' type because index expression is not of type 'number'.
How can I solve this?
Upvotes: 1
Views: 311
Reputation: 327994
The enum
object named Policy
is not known to have values at every string
key; only the specific string literals "Admin"
and "Editor"
can be safely used. I assume you're not trying to support someone calling setPolicy("RandomString")
, right? So one way to fix this is to only allow the policy
argument to be the union of those types:
setPolicy(policy: "Admin" | "Editor") {
this.policy = Policy[policy];
}
Of course you don't want to have to edit that line every time you add or otherwise modify the keys of Policy
. So you can use the keyof
type operator to get the union of keys from the type of the Policy
object. Note that the type of the Policy
object is not Policy
, but typeof Policy
which uses the typeof
type operator. See this q/a for a long rant explanation about the difference between types and values in TypeScript. So you can do this:
setPolicy(policy: keyof typeof Policy) {
this.policy = Policy[policy];
}
The type keyof typeof Policy
is the same as "Admin" | "Editor"
, as you can see by inspecting it:
new Foo().setPolicy("Admin");
// setPolicy(policy: "Admin" | "Editor"): void
Upvotes: 3