如何在反应/打字稿中使用枚举

时间:2019-07-02 09:41:26

标签: reactjs typescript

关于枚举的三个示例如一,二,三。我调用函数以不同的参数进行响应。第二个结果使我感到困惑。我认为TS会像第一个示例一样检查类型并告诉我问题。(类型为“ test”的参数不能分配给类型为“ Response”的参数。ts)数字9没有在Response中退出但不会抛出错误!如何确保型号安全? (我的意思是,响应参数必须是枚举中包含的数字,而不是9或其他)

const enum Response {
  No = 0,
  Yes = 1
}

function respond(message: Response): void {
  console.log(message);
}

// one
respond("test");
// two
respond(9);
// three
respond(Response.Yes);

response params必须是包含在枚举Response中的数字,并且TS告诉我如何解决它。

3 个答案:

答案 0 :(得分:0)

在这种情况下,我认为正确的是定义这种情况的类型。

// you can export these to use around app
export const YES = 'YES';
export const NO = 'NO';

type TypeSafeResponse = 'YES' | 'NO';

// this one errors like it should
const response: TypeSafeResponse = 3;
// this one errors like it should
const response2: TypeSafeResponse = 'test';
// this one is allowed like it should
const response3: TypeSafeResponse = YES;

从而确保您的应用是类型安全的。

答案 1 :(得分:0)

我找到了感觉很好的答案。

实际上只有数字值的任何枚举实际上只是数字的别名-您可以分配不在枚举中的值。原因是枚举经常被用作位域,因此它需要能够表示诸如标志标志B |标志C。

如果您想要更安全的类型枚举,则可以尝试使用字符串值而不是数字。

https://github.com/microsoft/TypeScript/issues/32227

答案 2 :(得分:0)

您在另一个问题中使用enum要求替代。您可以使用枚举来确定答案,而在原始问题中不允许使用9之类的整数。

例如,使用:

const enum MyResponse {
  No = "No",
  Yes = "Yes"
}

function respond(message: MyResponse): void {
  console.log(message);
}

将允许写作:

respond(MyResponse.No);

不允许传递数字:

respond(9);