网站搜索

如何将 Typescript 枚举用作函数参数?


当我将枚举作为函数参数使用时,我很难获得类型安全。例如,使用 TS 枚举文档中的示例代码:

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...
  • 为什么在使用 5 这个在 UserResponse 中未定义的值时,编译器没有报错?
  • 我如何改进类型定义,使得 message 参数只接受 UserResponse.Yes | UserResponse.No?
  • 我是否应该使用其他数据结构来存储 UserResponse?

答案#1

这个问题不幸的是重复的。不过,这意味着已经有一个答案:https://stackoverflow.com/a/49169301/12425097 - 看起来你最好的选择是使用字符串枚举,或者使用在链接答案中演示的命名空间类型联合。