How can one break down enum values in typescript?

I've defined an enum in TypeScript as shown below:

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

Now, I want to destructure its value. How can we achieve this in TypeScript?

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

Update

As per @amadan's suggestion shared in this post, we can utilize the method of Assigning to new variable names explained in the Mozilla documentation on Destructuring Assignment. Here's how it works:

Assigning to new variable names

A property from an object can be unpacked and assigned to a variable with a different name than the original object property.

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

This technique is effective for solving the problem at hand. However, if you need access to all items without explicitly defining them, consider using either of the methods mentioned in tag1 or tag2.

Answer №1

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

The issue arises because the object XMPPElementName does not contain keys like uc, and others. By assigning specific names to the keys, you can resolve this problem:

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

This solution will resolve the issue. Alternatively, you may choose to use variables with names that match the keys, rather than the values themselves:

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

Answer №2

If you're looking to create a mapping of enum values in JavaScript, you can utilize a utility type for generating the appropriate structure. Keep in mind that enums in JS are essentially plain objects.

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]))
}

Check out this Playground Link

Answer №3

In TypeScript, enums are similar to regular JavaScript objects as demonstrated in the playground or console logs:

https://i.sstatic.net/KN90A.png

An approach involves using a function that creates a new object with a {value: value} structure. Here's an example:

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

const { option1, option2, message, labelSize, sizeIndex, type, content } = mapEnumValuesToObject(
  EnumName
); 

We welcome TypeScript-specific solutions!

Answer №4

If you're in need of a quick and straightforward solution, rest assured that yes, it is indeed possible (at least for now). This method seems to work seamlessly whether you are dealing with enums that have assigned values or not.

enum MyEnum {
  One,
  Two,
  Three
}

const { One, Two, Three } = myEnum;

console.log({ One, Two, Three }) // {One: 0, Two: 1, Three: 2}

enum Status {
   None = '',
   Created = 'CREATED',
   Completed = 'COMPLETED',
   Failed = 'FAILED',
}

const { None, Created, Completed, Failed } = Status;

console.log(None, Created, Completed, Failed) // '', 'CREATED', 'COMPLETED, 'FAILED'

If you happen to discover any discrepancies while testing this out on your own, please don't hesitate to reach out and let me know.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for restricting AJAX requests to the same domain?

I'm puzzled by the limitation of AJAX requests to the same domain. Can you explain the reasoning behind this restriction? I don't understand why requesting files from external locations is an issue, especially since servers making XMLHTTP reques ...

Creating a constant in an AngularJS module: The definitive guide to defining module-specific constants

Within a page, numerous Angular modules are present. I have set up a constant for each module containing the version number. var module1 = angular.module('module1').constant('version', '1.2.3'); var module2 = angular.module(& ...

What is the best way to conceal the standard 'X' close button within a magnific popup interface?

I implemented the Magnific-popup plugin in my jsp to show messages to users. Here is the code I used to open Magnific Popup: $.magnificPopup.open({ items: { type: 'inline', src: '#idOfSomeDivInPage' }, focus: '#some ...

issues with jquery's .each() method not functioning properly

I am looking to iterate over each item in lists and then each list within lists to calculate the number of items in list if the number of items in list is 3, I want to display an alert with the value of each item JSON Data { "lists":[ { ...

MUI version 5 - Checkboxes are receiving a variety of unique classes

After recently upgrading from Mui v4 to v5, I've noticed a strange behavior with checkboxes. Upon inspecting the DOM differences between the two versions, it appears that some additional classes are now being applied in v5 and the extra span with the ...

Exploring the Power of Ajax Integration with Mongodb

I have been trying to figure this out for a while now, but I'm lost. I am attempting to use Ajax to retrieve information from a collection named 'reizen' in MongoDB. My goal is to cycle through all elements within the collection and extract ...

Troubleshooting problems with the width of a Bootstrap navbar

I'm encountering a frustrating issue with my bootstrap menu. When I include the "navbar Form" in the menu, the width of the menu extends beyond the screen width in mobile mode (when resizing the browser window or viewing on a mobile device). Interesti ...

There appears to be a malfunction with WebRupee

I have incorporated the new rupee sign into my website to represent Indian currency. Below is the code snippet I used: For the script, I included " and also added the following: <span class="WebRupee">Rs.</span> 116,754.00 To style it using ...

Control the playback of individual HTML5 audio elements using jQuery for seamless user experience

How can I modify the code to ensure that only one HTML5 audio element plays at a time? Currently, all tracks are able to play simultaneously. I am using jQuery for play and pause functionalities. If one track is playing and another is clicked on, how can ...

Guide on toggling mat-checkbox according to API feedback in Angular 6

Just starting out with angular 6 and I'm attempting to toggle the mat-checkbox based on the API response. However, I seem to be having trouble. All the checkboxes are showing as checked even when the API response is false. <div class="col-sm-12" ...

unusual behavior observed in addEventListener

I have recently delved into learning about the DOM. I have a project in mind where I want to create a website with buttons that, when clicked, play different drum sounds. As part of my experimentation with JavaScript, I wanted to explore the this keyword. ...

Using React refs to target multiple elements dynamically with the help of the map

My code effectively catches when the dropdown is clicked outside, and it's working well: displayOptions() { return _.map(this.props.selections, (option, index) => { return ( <div className="ui icon top dropdown" ...

What is the process of creating a MaterialUI checkbox named "Badge"?

Badge API at https://material-ui.com/api/badge/ includes a prop called component that accepts either a string for a DOM element or a component. In my code: <Badge color="primary" classes={{ badge: classes.badge }} component="checkbox"> <Avatar ...

Methods for adding a line to an array

I am currently working on a loop where I need to populate my array called photos: $scope.photos = []; var str = data.data.Photos; var res = str.split('|'); angular.forEach(res, function (item) { ...

What is the preferred method for accessing nested object properties in React props?

Building upon a previous inquiry - Javascript - How do I access properties of objects nested within other Objects It appears that standard dot notation doesn't suffice for accessing nested object properties within React state/props. In the case of t ...

Techniques, modules and functions in Javascript

How should I properly document this code snippet: // Define a collection of colors with methods colors = { // Define method for color red "red" : function() { // Do something... } // Define object for color black "black" : { // Add ...

Unable to establish breakpoints in TypeScript within VS Code

I seem to be facing an issue while trying to set breakpoints in my TypeScript nodejs app using Visual Studio Code. Despite following the guidelines provided on the Visual Studio Code website, I have not been able to achieve success. Below is the content o ...

Is there a way to display my array within my React component using JavaScript?

I am working with an element that looks like this: const DropdownElements = [ { key: 1, title: "City", placeholder: "Select City", apiUrl: "https://api.npoint.io/995de746afde6410e3bd", type: "city&qu ...

The issue of AFrame content failing to display on Google Chrome when used with hyperHTML

There seems to be an issue with A-Frame content not rendering on Chrome, despite working fine on FireFox and Safari. According to the demonstration on CodePen here, const { hyper, wire } = hyperHTML; class Box extends hyper.Component { render() { retu ...

Why does TypeScript assign parameters in the opposite direction when assigning callbacks?

When a function is called with an argument, the argument type is matched to the parameter type. This means that the argument type must be the same as, or more specific than, the parameter type. For example: const foo = (bar: string | number) => { con ...