#Case Insensitive String to Enum | undefined

15 messages · Page 1 of 1 (latest)

wheat dew
#

The goal is to convert a string (case-insensitive) to an enum value, or undefined if not present. Here is what I have so far:

// enum generated by graphql codegen
enum ItemType {
  Club = 'CLUB',
  Comment = 'COMMENT',
  // and more...
}

function toItemType(type:string):ItemType|undefined {
  return ItemType[type as keyof typeof ItemType]
}

console.log(toItemType("Comment")) // COMMENT
console.log(toItemType("comment")) // undefined
console.log(toItemType("COMMENT")) // undefined

This code appears to key off the enum-name Comment, not the enum-value "COMMENT".

The enums are generated by graphql-codegen, which appears to CammelCase the name. The enum string-values are always UPPER_CASE.

I also do want it to return undefined if values are not present (either upper or lower-case), so that behavior is intended.

arctic sleetBOT
#
tagr-jg#4605

Preview:```ts
enum ItemType {
Club = 'CLUB',
Comment = 'COMMENT',
// and more...
}

function toItemType(type:string):ItemType|undefined {
return ItemType[type as keyof typeof ItemType]
}

console.log(toItemType("Comment")) // COMMENT
console.log(toItemType("comment")) // undefined
...```

opal trench
#

The example was for a union type though, but I guess the logic would be similar

#

Let me think how to define it 🤔

arctic crane
#

@wheat dew what are you trying to do exactly?
what should be the right values?

#

want the 3 function calls to return the enum member?

#

in this case, the following code should do

function toItemType(type: string) {
  return Object
    .values(ItemType)
    .find(value => value === type.toUpperCase());
}
#

keep in mind enums are simply objects at runtime, you can use the usual method on them

opal trench
arctic crane
wheat dew
#

This specific use-case takes a string from a URL parameter, and uses it to create a graphql query. So, it is not called very often.

#

Ideally, yes, all 3 function calls should return the same enum member, ignoring capitalization of the input.

#

I'll give the last code snippet a try. That seems more inline with what I'm wanting to do, and with other future use-cases that might need it.

#

That works in typescript playground, thank you @opal trench and @arctic crane