1

I have a Typescript enum...

enum Animals {
  CAT = 'cat',
  DOG = 'dog',
  FISH = 'fish'
}

I have a function who's parameter can be one of the values of the enum. How do I type that??

function getAnimal (param: ValueOf<Animal>) {
  return 'Your animal is a ' + param; 
}

The goal is for me to be able to export this function elsewhere in my code, and get the intellisense to say that param can be 'cat'|'dog'|'fish'

TJBlackman
  • 1,895
  • 3
  • 20
  • 46
  • https://stackoverflow.com/questions/52393730/typescript-string-literal-union-type-from-enum – Psidom Aug 02 '20 at 17:52
  • Thanks! I didn't know what key words to use to ask this question, even though I was sure I wasn't the first to ask it. – TJBlackman Aug 02 '20 at 18:01

1 Answers1

2
enum Animals {
  cat = 'cat',
  dog = 'dog',
  fish = 'fish'
}

function getAnimal (param: keyof typeof Animals) {
  return 'Your animal is a ' + param; 
}
critrange
  • 5,652
  • 2
  • 16
  • 47