What is the best way to loop through a combination of strings and numbers in an enum using TypeScript

enum MixedEnum {
  A = 1,
  B = 'b',
  C = 'B',
  D = '2'
}

This code presents a unique scenario of mixing strings and numbers in an enum. The objective is to iterate through the values of MixedEnum, such as displaying them in an array like [1, 'b', 'B', '2'] or showcasing their keys as ['A', 'B', 'C', 'D']. Is there a straightforward method to achieve this goal?

Answer №1

Why use a mixed enum like this? I didn't realize that was even possible!

As you may be aware, when it comes to number-valued enum members, both the key and the value are stored on the MixedEnum object. On the other hand, string-valued members only have their key saved. This means that when iterating through the keys, you need to filter out numeric-named members of MixedEnum. The TypeScript checker provides guidance on how to perform this filtering in an efficient way:

if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) {
    error(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name);
}

Here's the corresponding function used for filtering:

function isNumericLiteralName(name: string | __String) {
    // [comments omitted]
    return (+name).toString() === name;
}

With this in mind, the code snippet for iteration would look something like this:

for (let item in MixedEnum) { 
  if ((+item).toString() === item && 0 * (+item) === 0) continue;
  // item represents a key, while MixedEnum[item] corresponds to its value - proceed with processing
}

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

Understanding the timing of records being returned via an Observable in Angular's ngOnInit

In my Angular 2 application, I am using an observable to keep track of an array of records. As the results of this observable are stored in the variable "records", I am utilizing *ngFor="let record of records" to iterate over and display them in my view. ...

Mapping an array of Type T in Typescript using typings

Suppose we have a type T: type T = { type: string, } and we create a function that takes an array of T and returns an object where the keys are the values of each T.type and the values are objects of type T. const toMap = (...args: T[]) => args.red ...

Combining two elements in Angular 2

I am looking to find the intersection of two objects. My goal is to compare these objects and if they have matching values on corresponding keys, then I want to add them to a new object. obj1 = { "Projects": [ "test" ], "Companies": [ "facebook", "google ...

Modifying app aesthetics on-the-fly in Angular

I am currently working on implementing various color schemes to customize our app, and I want Angular to dynamically apply one based on user preferences. In our scenario, the UI will be accessed by multiple clients, each with their own preferred color sch ...

What causes the act of clicking a button to alter a particular section of my vscode extension to seem so detrimental?

Background Language used : typescript UI toolkit svelte and bootstrap Description of Problem I am currently developing a vscode extension where clicking a button should update an HTML table element in the view based on the button clicked. Here is the type ...

How to access the extended interface from the base interface in TypeScript

I am working with an interface that contains an array of itself as children elements. interface MyNestedInterface { value: string; children?: ReadonlyArray<MyNestedInterface>; } My goal is to ensure that the objects are only one level deep in th ...

Material-UI Alert: The property `onKeyboardFocus` for event handling is unrecognized and will not be applied

Here is a more detailed trace of the issue: warning.js:33 Warning: Unknown event handler property `onKeyboardFocus`. It will be ignored. in div (created by IconMenu) in div (created by IconMenu) in IconMenu (created by DropdownMenu) in div ...

What is the best method for eliminating unsuccessful retries in BullMQ tasks?

I am utilizing BullMQ to run background jobs. My main job is defined with a retry strategy, and I want to ensure that if the main job fails and then its retried attempt fails as well, the failed retries are automatically removed. Since I calculate error th ...

No error was flagged when the function had the potential to return undefined

getStage may sometimes return undefined without reporting any errors, which could potentially lead to a code crash. const a = Math.random() > 0.4 function getStage(): string { if(a) { return '' } } c ...

Avoid using React refs for managing Popups

Recently, I've been using a pattern based on refs that seems to go against the advice given in the React documentation. This is how the pattern works: type Callback = () => void; type CallbackWrapper = {callback : Callback} interface IWarningPop ...

What situations call for the use of 'import * as' in TypeScript?

Attempting to construct a cognitive framework for understanding the functionality of import * as Blah. Take, for instance: import * as StackTrace from 'stacktrace-js'; How does this operation function and in what scenarios should we utilize imp ...

Using rxjs for exponential backoff strategy

Exploring the Angular 7 documentation, I came across a practical example showcasing the usage of rxjs Observables to implement an exponential backoff strategy for an AJAX request: import { pipe, range, timer, zip } from 'rxjs'; import { ajax } f ...

Ensure the CSS class stays on Quill clipboard.dangerouslyPasteHTML

One of the challenges I face with using the Quill Text Editor is that when I use the method clipboard.dangerouslyPasteHTML to paste HTML into the editor, it does not maintain custom CSS classes. For example: let content= '<p class="perso-clas ...

Injecting a service into a base class in Angular/TypeScript without injecting it into a sub-class

I am working with a basic ServiceBase class that has Http injected into its constructor: import { Headers, Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; export abstract class ServiceBase<T> { constructor ...

Leveraging Filter in Typescript and Ionic for Object Manipulation

I'm currently utilizing Ionic 3.x framework. I have developed a simple chat application and now I need to implement a feature that allows filtering chats based on specific words. To achieve this, I decided to add a search bar to my application. Here ...

NGXS TypeError: Freezing not possible in Angular

https://i.sstatic.net/uD6Vp.png The block of code responsible for triggering the specified action constructor(auth: AuthService, private store: Store) { this.userAuth = auth.signedIn.subscribe({ next: (user) => { this.user = user; thi ...

"Experiencing issues retrieving user-modified values in NativeScript's TimePicker component

I'm having trouble retrieving the user-modified value from a TimePicker. Instead of getting the modified value, I keep receiving the original value that was initially set in the control. Below is my component template: <TabView [(ngModel)]="tabSe ...

What benefits do Definitely Typed TypeScript files offer for Knockout and jQuery?

I'm not sure if this is a silly question, but I was wondering if it's necessary to use definitely typed (.d.ts) versions of external libraries when working with Typescript. Currently, my code base uses jQuery and Knockout in the traditional manne ...

Updating an array by adding or removing items

I am attempting to create a method for deleting and adding items to an array, but I need easy-to-use delete and add methods since I am unfamiliar with TypeScript. export class NgForComponent implements OnInit { Numbers: number[]; constructor() { ...

What is the best way to pass only the second parameter to a function in TypeScript?

Let's consider a TypeScript function as shown below: openMultipleAddFormModal(commission?: Commission, people?: People): void { // some data } To make a parameter optional, I have added the Optional Chaining operator. Now, how can I modify the code ...