0

I was looking for a similar case in the SO resources but I couldn't find similar topic, so I'm posting my question here.

How can I get returned enum value, based on providing its type name as parameter?

i.e I'd pass as a parameter this "ResetPasswordUrl" and I would like to return this "//a[contains(@href, 'reset-password')]/@href" expression as a result

enum CustomXPathExpressions {
ResetPasswordUrl = "//a[contains(@href, 'reset-password')]/@href",
OtherExpression = "//div" }
 
public getCustomExpressionValue(option: CustomXPathExpressions ) {
 
return here
 
}
ArturS
  • 723
  • 1
  • 6
  • 19

2 Answers2

2

return option.valueOf(); would do the thing you want to achieve.

Robert Kossendey
  • 6,733
  • 2
  • 12
  • 42
  • Thanks a lot will check it out :P, hope this will work :P – ArturS Sep 01 '20 at 12:01
  • That's a no-op, though. `option` is itself a string, so `return option` also works. – jcalz Sep 01 '20 at 13:42
  • Yep I've faced the same problem as You've described, I should probably convert the string to the Enum key @jcalz how could I achieve this :p? – ArturS Sep 01 '20 at 14:02
1

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

jcalz
  • 264,269
  • 27
  • 359
  • 360
  • Thanks a lot jcalz, for brilliant introduction to what really enum is in Typescript, I'll check it out :P – ArturS Sep 01 '20 at 14:15