【问题标题】:how to map enum values to type in typescript如何将枚举值映射到打字稿中
【发布时间】:2020-12-07 00:14:56
【问题描述】:

我有一个枚举类型,看起来像这样:

export enum API_TYPE {
  INDEX = "index_api",
  CREATE = "create_api",
  SHOW = "show_api",
  UPDATE = "update_api",
  DELETE = "destroy_api"
};

现在,我有一个接受数字和 api_type 参数的函数

export function abc (id: number, api_type:?) => 

对于这个函数,api_type 的可能值是枚举键的值 api_type

讨论function abcapi_type 参数类型的最佳方式是什么?

一种方法是export type Api_Type = "index_api" | "create_api" | "show_api" | "update_api" | "destroy_api"

然后

export function abc (id: number, api_type:Api_Type) => 

但是如果我将新属性(键)添加到 enum API_TYPE {,我还必须记住手动将其添加到Api_Type

有没有办法,我可以将枚举值映射到一个类型?还是更好的方法?

【问题讨论】:

  • 执行此操作的正常方法是function abc(id: number, api_type: API_TYPE),您可以将其称为abc(123, API_TYPE.INDEX),而不是abc(123, "index_api")。如果这对您不起作用,请详细说明。

标签: typescript


【解决方案1】:
enum ApiType {
  INDEX = "index_api",
  CREATE = "create_api",
  SHOW = "show_api",
  UPDATE = "update_api",
  DELETE = "destroy_api"
};

 function abc (id: number, api_type:ApiType) {
    console.log(api_type);
 }

这是Demo Link

【讨论】:

    猜你喜欢
    • 2020-09-16
    • 1970-01-01
    • 2022-12-12
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 2021-11-09
    • 2022-10-25
    • 1970-01-01
    相关资源
    最近更新 更多