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'

2
  • stackoverflow.com/questions/52393730/… Commented Aug 2, 2020 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. Commented Aug 2, 2020 at 18:01

1 Answer 1

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

function getAnimal (param: keyof typeof Animals) {
  return 'Your animal is a ' + param; 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.