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
Playground link to code