我有这个枚举
enum methods {
DELETE = 1,
POST,
PUT,
GET
}
我希望有一个函数接受一个参数,该参数可以是methods
枚举的键之一。
const getMethodPriority = (method /* how do I type this? */) => {
return methods[method];
};
因此,例如getMethodPriority("DELETE")
会返回1
。
如何输入method
参数?
答案 0 :(得分:2)
您可以通过将数值转换为number
来直接从数字枚举中获取数字:
enum methods {
DELETE = 1,
POST = 2,
PUT = 3,
GET = 4
}
let enumPriority = methods.DELETE as number;
// enumPriority == 1
但如果你真的想要一个方法,你可以:
enum methods {
DELETE = 1,
POST = 2,
PUT = 3,
GET = 4
}
const getMethodPriority = (method: keyof typeof methods) => {
return methods[method];
};
// how to call
getMethodPriority("DELETE");
答案 1 :(得分:0)
使用keyof
和typeof
运算符,如下所示:
enum methods {
DELETE = 1,
POST,
PUT,
GET
}
const getMethodPriority = (method: keyof typeof methods) => {
return methods[method];
};