【问题标题】:Typescript: enum keys as parameter to function打字稿:枚举键作为函数的参数
【发布时间】:2018-02-24 13:41:57
【问题描述】:

我有这个枚举

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

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

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

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

如何输入method 参数?

【问题讨论】:

  • 你可以和(method: keyof typeof methods)一起去

标签: typescript


【解决方案1】:

您可以通过将数字枚举的值转换为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");

【讨论】:

  • 对不起!! methodPriorities 应该只是methods。请查看我更新的getMethodPriority 函数
  • 如果是这样 - 你不需要任何功能 - 只需转换为我在 PS 部分中写的数字。
  • 作为使用keyof typeof 组合的额外好处,您还可以对复合枚举进行类型检查,例如稍后解压缩的点分隔路径字符串,如'property.subprop.field' - 这是不可能的直接枚举引用。
【解决方案2】:

像这样使用keyoftypeof 运算符:

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

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

【讨论】:

    猜你喜欢
    • 2019-09-25
    • 2018-05-22
    • 2019-03-04
    • 2018-07-05
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    相关资源
    最近更新 更多