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:

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

How can one access a specific element by its id that is located within an ng-template in Angular 6?

I have a question regarding accessing a button element inside an ng-template tag using its id in the TypeScript file. How can I accomplish that without encountering undefined errors? This is what I have tried so far: HTML <ng-template #popup > ...

The debate between using "this" versus "classname" to access static elements in

When working with TypeScript, I've observed that there are multiple valid approaches for accessing a static class member. class MyClass { private static readonly FOO: string = "foo"; public DoSomething(): void { console.log(MyClass.FOO);} pu ...

What is the best way to collapse a button in asp.net using javascript after setting it to hidden?

I have a scenario where I have 3 buttons in a row on my asp.net page. Using JavaScript, I am setting the middle button (ButtonSR) to invisible. However, I want the button below it to move up and take its place instead of leaving an empty space. ...

What is the best way to prevent a folder from being included in the next js build process while still allowing

I am faced with a challenge involving a collection of JSON files in a folder. I need to prevent this folder from being included in the build process as it would inflate the size of the build. However, I still require access to the data stored in these file ...

Find all Mondays occurring within a specified date range using Moment.js

I need to extract all Mondays within a specific date range. let start = moment(this.absence.FromDate); let end = moment(this.absence.ToDate); The user has the option to deactivate certain weekdays during this period by setting booleans. monday = true; t ...

Guide to inspecting file contents with Node.js

I am working on viewing the content of a file that is posted from the client using the fs module. However, with the code below, the contents are coming up as undefined. Can anyone help me identify what is missing in the code? To ensure I am receiving the ...

Adding Typescript to a Nativescript-Vue project: A step-by-step guide

Struggling over the past couple of days to configure Typescript in a basic template-generated Nativescript-Vue project has been quite the challenge. Here's my journey: Initiated the project using this command: ERROR in Entry module not found: Erro ...

Typescript's ability to have Enums with dynamic keys

Suppose I define: enum Sort { nameAsc = 'nameAsc', nameDesc = 'nameDesc' } Is it possible to do the following? const key = 'name' + 'Desc'; Sort[key] Appreciate any help in advance ...

Creating a customizable range input for pixel values: a step-by-step guide

I am looking to design a pixel range input. Here is an example: let slider = document.querySelector("input"); slider.addEventListener("change", () => { console.log(slider.value); }); <input type="range" min="5px" max="50px"> However, the r ...

Transitioning a JavaScriptIonicAngular 1 application to TypescriptIonic 2Angular 2 application

I am currently in the process of transitioning an App from JavaScript\Ionic\Angular1 to Typescript\Ionic2\Angular2 one file at a time. I have extensively researched various guides on migrating between these technologies, completed the A ...

Using Node.js to create a server that utilizes JSON.stringify for handling deep object

My question may seem simple, but I have yet to find a perfect answer that is completely clear to me. The question at hand is: How can I return MongoDB from "collection.findOne" with mongo and then use JSON.stringify() to send this information to another s ...

There is an issue with types in React when using TypeScript: The type '(user: User) => Element' cannot be assigned to the type '((props: User) => any) & ReactNode'

I'm encountering an error in the terminal and need some assistance. I am not well-versed in TypeScript, so any guidance to resolve this issue would be highly appreciated. https://i.stack.imgur.com/PWATV.png The Loadable component code: import { Circ ...

In Next.js, the elements inside the div created by glider-js are not properly loaded

I'm currently working on setting up a carousel in nextjs using the data retrieved from an API and utilizing glider-js for this purpose. However, I'm facing an issue where the div created by glinder-js does not include the elements that are render ...

Probability of an event occurring when represented as whole numbers in percentage form

Currently, I'm developing a unique job system within a Discord bot that allows users to mine various types of ores. The probability of receiving specific ores is based on the user's mining skill level, which is stored in a database and can vary a ...

I'm looking for assistance on how to execute a render right after making a put or delete request

class ProductApp extends Component { constructor() { super(); this.state = { currentProduct: null, items: [], }; this.handleUpdateSubmit= this.handleUpdateSubmit.bind(this); } componentDidMount() { axios.get('h ...

Creating dynamic content with Express.js: Using variables in EJS within the request handler

I am looking for a way to include additional variables to be utilized by EJS during the rendering of a view for every request, similar to adding them in the render function: res.render('view', {data: {my: 'object'}}); I have implement ...

lengthy conditional statement in JavaScript

Is there a more efficient way to handle a long series of if-else statements in JavaScript? I'm not experienced enough with the language to optimize this code. Any suggestions or guidance would be greatly appreciated. $('#webform-component-primar ...

Calling Ajax in JavaScript

Trying to fetch a value in JavaScript using an Ajax Call, The code being used is as follows: <script> var value = $.ajax({ type:"GET", url:"get_result.php", data:"{'abc':" + $abc + "}", }); alert(val ...

Choose only one option from the dropdown menu at a time within the specified div

I attempted to utilize the "setSelected" option on my multiselect feature, but I noticed that it does not function with div elements (at least I could not make it work myself). I am endeavoring to create two synchronized multiselects using this example: b ...

Incorporate a new item into an array within DynamoDB that does not currently

I am attempting to update an attribute called items, which is a list of strings. Is it possible to update (append) the attribute only if it does not already exist? Something like a combination of list_append and if_not_exists. var params = { ... Upda ...