打字稿:枚举键作为函数的参数

时间:2018-02-19 20:30:33

标签: typescript

我有这个枚举

enum methods {
  DELETE = 1,
  POST,
  PUT,
  GET
}

我希望有一个函数接受一个参数,该参数可以是methods枚举的键之一。

const getMethodPriority = (method /* how do I type this? */) => {
  return methods[method];
};

因此,例如getMethodPriority("DELETE")会返回1

如何输入method参数?

2 个答案:

答案 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)

使用keyoftypeof运算符,如下所示:

enum methods {
  DELETE = 1,
  POST,
  PUT,
  GET
}

const getMethodPriority = (method: keyof typeof methods) => {
    return methods[method];
};