Is it possible to retrieve and utilize multiple Enum values in Typescript?

Combine enum values to retrieve corresponding enum strings.

Consider the following scenario:

enum EnumDays {
    NONE = 0,
    SUN = 1,
    MON = 2,
    TUE = 4,
    WED = 8,
    THU = 16,
    FRI = 32,
    SAT = 64,
    ALL = 127
}

If I pass a value of 5, which represents SUN & TUE (1 + 4 = 5).

I intend to receive "SUN" & "TUE" as the output. How can this be achieved?

Answer №1

To tackle this task, one method is to iterate through the bits or enum members. The bit iteration approach appears more streamlined. Here, we exploit the fact that EnumDays links values to keys (for example, 1 corresponds to SUN) and keys to values (SUN corresponds to 1). It's worth noting that this method may not identify an enum value of 2147483648. Using 1 << 31, resulting in -2147483648, will provide a solution.

function getDayNames(value: EnumDays) {
    let names = [];
    for (let bit = 1; bit != 0; bit <<= 1) { 
        if ((value & bit) != 0 && bit in EnumDays) { 
            names.push(EnumDays[bit]);
        }
    }
    return names;
}

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 most effective approach to scan Angular 2, 4, 5 template html files before AOT compilation for optimal code quality assessment?

Recently, I stumbled upon an interesting GitHub repository called "gulp html angular validate". If you're not familiar with it, you can check it out here. However, I have doubts about whether this tool is suitable for Angular 2+ projects. Additionall ...

Deciding between bundling a Typescript package and using tsc: When is each approach the best choice

When it comes to publishing a Typescript NPM package (library, not client), I have two main options: 1. Leveraging Typescript's compiler First option is to use the Typescript compiler: tsc and configure a tsconfig.json file with an outDir setting: { ...

What is the process for obtaining a flattened tuple type from a tuple comprised of nested tuples?

Suppose I have a tuple comprised of additional tuples: type Data = [[3,5,7], [4,9], [0,1,10,9]]; I am looking to develop a utility type called Merge<T> in such a way that Merge<Data> outputs: type MergedData = Merge<Data>; // type Merged ...

developing TypeScript classes in individual files and integrating them into Angular 2 components

We are currently putting together a new App using Angular2 and typescript. Is there a more organized method for defining all the classes and interfaces in separate files and then referencing them within angular2 components? import {Component, OnInit, Pi ...

The cursor in the Monaco editor from @monaco-editor/react is not aligning with the correct position

One issue I am facing with my Monaco editor is that the cursor is always placed before the current character rather than after it. For example, when typing a word like "policy", the cursor should be placed after the last character "y" but instead, it&apos ...

Using Typescript, the type T or a function that returns T can be utilized in various scenarios

You can check out a demonstration on this interactive platform. In creating a simple generic type that represents either a variable or a function returning a variable, there was an issue with the typical typeof arg === 'function' check. The erro ...

Combining type inference validation and authentication middleware in Express routes can be a powerful way to enhance security and ensure

I am struggling to grasp how types are automatically determined in Express routes when utilizing multiple middlewares. To conduct validation using zod, I have employed the middleware package express-zod-safe, although a similar issue arose with alternativ ...

Blending ASP.NET Core 2.0 Razor with Angular 4 for a Dynamic Web Experience

I am currently running an application on ASP.NET Core 2.0 with the Razor Engine (.cshtml) and I am interested in integrating Angular 4 to improve data binding from AJAX calls, moving away from traditional jQuery methods. What are the necessary steps I need ...

Can the ngx-chips library be used to alter the language of chips?

Currently, I am working with the ngx-chips library and encountering a particular issue. Here is an image representation of the problem: The challenge I am facing involves updating the language of the chips based on the selection made in a dropdown menu. A ...

Setting up WebPack for TypeScript with import functionality

A tutorial on webpack configuration for typescript typically demonstrates the following: const path = require('path'); module.exports = { ... } Is it more advantageous to utilize ES modules and configure it with import statements instead? Or is ...

Create a three-dimensional tree array in Typescript/Javascript by transforming a flat array

Received data is structured as follows: const worldMap = [ { "name": "Germany", "parentId": null, "type": "Country", "value": "country:unique:key:1234", "id&qu ...

Tips for changing a function signature from an external TypeScript library

Is it possible to replace the function signature of an external package with custom types? Imagine using an external package called translationpackage and wanting to utilize its translate function. The original function signature from the package is: // ...

The search is on for the elusive object that Angular 2/4

Why am I encountering the error message saying "Cannot find name 'object'"? The error message is: Error: core.service.ts (19,23): Cannot find name 'object'. This error occurs in the following line of code: userChange: Subject<ob ...

Is Angular Template Polymorphism Failing?

So I'm working with a base class that has another class extending it. export class Person { public name: string; public age: number; } export class Teacher extends Person { public yearsTeaching: number; } Now, in my component, I need to ...

Compiling fails when creating an object literal with a generic key

I am attempting to accomplish the following task. function createRecord<T extends string>(key: T) : Record<T, T> { return {[key]: key}; // Type '{ [x: string]: T; }' is not assignable to type 'Record<T, T>' } Howe ...

What sets apart the utilization of add versus finalize in rxjs?

It appears that both of these code snippets achieve the same outcome: Add this.test$.pipe(take(1)).subscribe().add(() => console.log('added')); Finalize this.test$.pipe(take(1), finalize(() => console.log('finalized'))).sub ...

The ngOnChanges lifecycle hook does not trigger when the same value is updated repeatedly

Within my appComponent.ts file, I have a property called: this._userMessage Afterwards, I pass it to the childComponent like so: <child-component [p_sUserMessage]='_userMessage'></child-component> In the childComponent.ts file: @ ...

Nest is unable to resolve DataSource in the dependency injection

I've encountered an issue with dependencies while working on my NestJS project. When I try to launch the app, the compiler throws this error at me: [Nest] 16004 - 09.04.2022, 16:14:46 ERROR [ExceptionHandler] Nest can't resolve dependencies of ...

Issue with Angular Checkbox: Inconsistencies in reflection of changes

I'm encountering a challenge with my Angular application where I have implemented multiple checkboxes within an options form. The issue arises when changes made to the checkboxes are not consistently displayed as expected. Below is the pertinent code ...

Utilizing Angular2 with Firebase for efficient denormalized data queries

I am currently working on crafting a query for a denormalized database. Drawing inspiration from the example showcased in Firebase's blog post, my objective is to: Retrieve the array of forms associated with the current user and return references to ...