How to use Typescript enum as function parameter?

Viewed 327

I'm struggling to get type safety when using enum as function parameters. For example, using the example code in the TS Enum docs:

enum UserResponse {
  No = 0,
  Yes = 1,
}

function respond(recipient: string, message: UserResponse): void {
  console.log(recipient, message)
}

respond("Princess Caroline", UserResponse.Yes);

respond("Princess Caroline", 'some other message'); // Argument of type '"some other message"' is not assignable to parameter of type 'UserResponse'.

respond("Princess Caroline", 5); // No error...
  • Why is the compiler not giving errors when using the value 5 which is not defined in UserResponse?
  • How can I improve the typings so that the message param ONLY accepts UserResponse.Yes | UserResponse.No?
  • Should I be using some other data structure to hold UserResponse?
1 Answers

This question is unfortunately a duplicate. However, that means there's already an answer: https://stackoverflow.com/a/49169301/12425097 - It looks like your best bets are to use a string enum, or a namespace type union which is demonstrated in the linked answer.

Related