If getCustomExpressionValue()
really takes "ResetPasswordUrl"
as its input, then option
is not of type CustomXPathExpressions
.
There's a bit of a confusing situation in TypeScript where there are named types (only exist at design time) and named values (that exist at runtime) and you can have a type named Foo
and a value named Foo
and they don't have to be related to each other. When you write enum Bar { k1="v1", k2="v2" }
you introduce a value named Bar
which is the enum object with property keys k1
and k2
whose property values are v1
and v2
. You also introduce a type named Bar
which is the union of the types of the enum object's property values, like "v1" | "v2"
. I have another answer which goes into painstaking detail on this.
Anyway, the type CustomXPathExpressions
is the type of the property value of the enum, not the type of the property key
. To get the type of the key, you need keyof typeof CustomXPathExpressions
. And that means you will be returning the enum value, which is type CustomXPathExpression
. So your function should look like:
function getCustomExpressionValue(
option: keyof typeof CustomXPathExpressions
): CustomXPathExpressions {
return CustomXPathExpressions[option];
}
And you can verify that it works:
console.log(getCustomExpressionValue("ResetPasswordUrl")); /*
//a[contains(@href, 'reset-password')]/@href */
console.log(getCustomExpressionValue("OtherExpression")); /* //div */
console.log(getCustomExpressionValue("bad key")); /* error! */
// -------------------------------> ~~~~~~~~~
// Argument of type '"bad key"' is not assignable to parameter of
// type '"ResetPasswordUrl" | "OtherExpression"'.
Playground link to code