2

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?
samzmann
  • 2,286
  • 3
  • 20
  • 47
  • I guess [this](https://stackoverflow.com/a/49198352/3388225) answers your question in good details. – aleksxor Jun 10 '21 at 12:03

1 Answers1

0

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.

LaytonGB
  • 1,384
  • 1
  • 6
  • 20