简体   繁体   English

如何在打字稿中解构枚举值?

[英]How to de-structure an enum values in typescript?

I have an enum in typescript like below:我在打字稿中有一个枚举,如下所示:

export enum XMPPElementName {
  state = "state",
  presence = "presence",
  iq = "iq",
  unreadCount = "uc",
  otherUserUnreadCount = "ouc",
  sequenceID = "si",
  lastSequenceID = "lsi",
  timeStamp = "t",
  body = "body",
  message = "message"
}

And wants to de-structure its value, How can we do this in Typescript?并且想要解构它的价值,我们如何在 Typescript 中做到这一点?

const { uc, ouc, msg, lsi, si, t, body } =  XMPPElementName; 

update更新

As @amadan mentioned , we can use Assigning to new variable names as in Mozilla doc say Destructuring_assignment , like below:正如@amadan提到的,我们可以像 Mozilla 文档中说的Destructuring_assignment那样使用Assigning to new variable names ,如下所示:

Assigning to new variable names分配给新的变量名

A property can be unpacked from an object and assigned to a variable with a different name than the object property.一个属性可以从一个对象中解包出来,并分配给一个与对象属性名称不同的变量。

const o = {p: 42, q: true};
const {p: foo, q: bar} = o;
 
console.log(foo); // 42 
console.log(bar); // true

And the method is very good to solve this problem, but if you need to access all items without the need to explicitly define them, you can either on of these two mentiond tag1 tag2并且该方法是非常好的解决了这个问题,但如果你需要访问的所有项目,而无需显式定义它们,您可以在这两个mentiond的标签1 TAG2

const { uc, ouc, msg, lsi, si, t, body } = XMPPElementName;

This doesn't work because XMPPElementName doesn't have an element named uc (and equivalently for others).这不起作用,因为XMPPElementName没有名为uc的元素(对于其他元素XMPPElementName如此)。 If you explicitly name your keys, it will work:如果您明确命名您的密钥,它将起作用:

  const {
    unreadCount: uc,
    otherUserUnreadCount: ouc,
    message: msg,
    lastSequenceID: lsi,
    sequenceID: si,
    timeStamp: t,
    body: body,
  } = XMPPElementName;

it will work.它会起作用。 Alternately, you can just use variables with names that are equal to the keys, not the values:或者,您可以只使用名称等于键的变量,而不是值:

  const {
    unreadCount,
    otherUserUnreadCount,
    message,
    lastSequenceID,
    sequenceID,
    timeStamp,
    body,
  } = XMPPElementName;

As we know, in typescript an enum is like a plain old javascript object(at-least what the playground js-output is showing or the log showing):正如我们所知,在打字稿中,枚举就像一个普通的旧 javascript 对象(至少是操场 js 输出显示的内容或日志显示的内容):

在此处输入图片说明

one way is using a function which generates a new object with {value:value} structure like below:一种方法是使用一个函数来生成一个具有{value:value}结构的新对象,如下所示:

export function convertEnumValuesToObject<T>(enumObj: T): { [index: string]: T[keyof T] } {
  const enum_values = Object.values(enumObj);
  return Object.assign({}, ...enum_values.map(_ => ({ [_]: _ })));
}

  const { uc, ouc, msg, lsi, si, t, body } = convertEnumValuesToObject(
      XMPPElementName
    ); 

It would be great to see answers in typescript?在打字稿中看到答案会很棒吗?

You want an enum value-to-value map.您需要一个枚举值到值的映射。 Like you've said enum in JS is just a POJO.就像你说 JS 中的 enum 只是一个 POJO。 You can create a utility type to help generate the correct type.您可以创建一个实用程序类型来帮助生成正确的类型。

type EnumValueMap<T extends { [k: string]: string }> = { [K in T[keyof T]]: K }

function convertEnumValuesToObject<T extends { [k: string]: string }>(enumerable: T): EnumValueMap<T> {
  return (Object as any).fromEntries(Object.values(enumerable).map(v => [v, v]))
}

Playground Link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何正确解构这个 JavaScript - How To De-Structure This JavaScript Properly 无法从 NextJS 中的 getStaticProps 解构道具? - Can't de-structure props from getStaticProps in NextJS? 在 async/await 中解构 Promise.all 的结果? - De-structure the result of Promise.all in async/await? Highchart 饼图,解构 dataLabels 并定义自定义格式化程序 - Highchart Pie chart, de-structure dataLabels and define custom formatter 获取数据提供了一些[资产]和[对象]。 我怎样才能在下面的代码中解构它们以便列出它们? - fetch data is providing some [assets] and [objects]. How can I de-structure these in the following code in order to list them out? React 和 Material UI,是否有一种简洁的方法来解构我发送给 useStyles 的道具 - React and Material UI, is there is a clean way to de-structure props that I am sending to useStyles 使用数组将预期事件参数解构为仅目标属性。 查找方法 - de-structure expected event parameter to just the target property , using array. find method 如何使用 typescript 将计算值分配给枚举 - How to assign computed values to enum using typescript 如何从 typescript 中的单个枚举值中获取所有枚举值? - How to get all enum values from a single enum value in typescript? 相反的枚举值TypeScript - Opposite enum values TypeScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM