typescript: checking if a string is part of an enum

2021-09-15

 | 

~1 min read

 | 

181 words

Say you have an enum and you use that to make sure that the values you assign are within a predefined list. What happens when you receive that value initially from an API as part of a JSON payload? Do you just hope that you received a known quantity? Or do you validate? If you validate, how?

Imagine you have an enum named Operation:

enum Operation {
  Add = "Add",
  Subtract = "Subtract",
}

When the app is transpiled, Operation will become

var Operation
;(function (Operation) {
  Operation["Add"] = "Add"
  Operation["Subtract"] = "Subtract"
})(Operation || (Operation = {}))

That is, it’s an object!

So, we can use that to our advantage and in our code use Object.values() to get the strings from the enum for comparison against the response from our API:

const included = Object.values(Operation).includes("Add")
const notIncluded = Object.values(Operation).includes("test")

While this works - it’s also probably/potentially a code smell if you’re relying on this! This is “fake” security. The better way to handle this is to have strong typing on what the functions accept.


Related Posts
  • 2021 Daily Journal


  • Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!