What specific category does the enum object fall under?

How can I create a wrapper class for a collection of elements in an enumeration?

export class Flags<ENUMERATION> {

    items = new Set<ENUMERATION>();

    enu;                // what type ?

    constructor(enu) {     // what type ?
        this.enu=enu;
    }

    set(id:ENUMERATION) { this.items.add(id); return this; }

     // For use: determine if a specific value is part of the enum or not
    setChecking(id:string):boolean{
        if (id in this.enu){
            let item = this.enu[id];
            this.items.add(item);
            return true;
        }
        return false;
    }
  // .....
}

Example:

    enum Props{ One, Two, Three };
    let fls=new U.Flags<Props>(Props);
    fls.set(Props.One);
    fls.set("asdf");          // TypeScript detects the wrong value
    fls.set(Props.Two);
    if (!fls.setChecking("xxxx"))  // Check external string against the enum set
        throw error

Question: What are the types of the 'enu' property and the parameter in the constructor, what is the type of the enum object?

If we specify the type in the constructor, we could write:

  let fls=new U.Flags(Props);

(TypeScript would infer the type from the constructor specification)

Answer №1

To represent the enum container object instead of the enum, you can modify the type parameter. The specific type of the enum would be

ENUMERATION[keyof ENUMERATION]>

export class Switcher<ENUMERATION extends { [P in keyof ENUMERATION]: any}> {

    options = new Set<ENUMERATION[keyof ENUMERATION]>();

    en: ENUMERATION;                // what type ?

    constructor(en: ENUMERATION) {     // what type ?
        this.en=en;
    }

    select(choice:ENUMERATION[keyof ENUMERATION]) { this.options.add(choice); return this; }

    // usage example: a random string points to an enum element or is not allowed
    validateSelection(value:string):boolean{
        if (value in this.en){
            let chosen = this.en[value as keyof ENUMERATION];
            this.options.add(chosen);
            return true;
        }
        return false;
    }
// .....
}

enum Choices{ First, Second, Third };
let swt=new Switcher(Choices);
swt.select(Choices.First);
swt.select("something");          // TypeScript picks up on the incorrect value
swt.select(Choices.Second);
if (!swt.validateSelection("invalid"))  // A separate string can be validated against the set/enum
{

}

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 issues can trailing white space cause in TypeScript coding?

While I understand that linting is the reason for this, why are trailing spaces considered problematic? I plan to disable this feature in tslint.json, but before I make that change, I want to ensure I'm not making a mistake. Visual Studio Code alert ...

Ways to define an interface that can accommodate various interfaces with a specific structure

I am in need of a function that can accept a parameter with interfaces having a specific structure. The parameter should be either a string hash or a string hash along with an attribute string hash, as shown below: { anotherHash: { a: 'a', ...

New substitute for extending the extent in OpenLayers 4

I am currently in the process of migrating my code from OpenLayers 3 to OpenLayers 4 using TypeScript. Previously, I had a code snippet that extended the extent of my map so that all vector shapes I drew would be visible upon loading... angular.forEach(w ...

Tips for Structuring Code in a Resource Management Phaser Typescript Project

I'm currently developing a resource-management game and require a "collection manager" to streamline interactions between states and objects in Typescript. Let's imagine the game revolves around nurturing cats. In one state, players advance time ...

Determining the Clicked Button in ReactJS

I need help with a simple coding requirement that involves detecting which button is clicked. Below is the code snippet: import React, { useState } from 'react' const App = () => { const data = [ ['Hotel 1A', ['A']], ...

What is the best way to implement record updates in a nodejs CRUD application using prisma, express, and typescript?

Seeking to establish a basic API in node js using express and prisma. The schema includes the following model for clients: model Clients { id String @id @default(uuid()) email String @unique name String address String t ...

Retrieving the value from a string Enum in Angular based on an integer

export enum RoleTypesEnum { RoleA = 'Role is A', RoleB = 'Role is B', } // in TypeScript file public RoleTypesEnum = RoleTypesEnum; I am trying to obtain the string value (e.g. Role is B) from an enum using an integer. If I u ...

Ways to access an observable's value without causing a new emit event

Is there a way to retrieve the value of an observable without causing it to emit again? I need this value for an ngClass expression. I attempted to use the tap operator within the pipe to access the values in switchMap, but the value is not being logged. ...

In TypeScript, this regular expression dialect does not permit the use of category shorthand

Recently, I attempted to implement a regular expression in TypeScript: I ran the following code: const pass = /^[\pL\pM\pN_-]+$/u.test(control.value) || !control.value; To my surprise, an error occurred: "Category shorthand not allowed in ...

Is the detection change triggered when default TS/JS Data types methods are called within an HTML template?

I'm currently updating an application where developers originally included function calls directly in the HTML templating, like this: <span>{{'getX()'}}</span> This resulted in the getX method being called after each change dete ...

After applying the withStyles and withTranslation higher order components to a React component, a Typescript error is displayed

Trying to create a React component using Typescript, incorporating withStyles from @material-ui/core and withTranslation from react-i18next, both of which are Higher Order Components (HOC). Encountering a typescript error when using them together. Specif ...

Ways to dynamically apply styles to the component tag depending on the visibility of its content

Consider a scenario where you have a component with logic to toggle the visibility of its contents: @Component({ selector: 'hello', template: `<div *ngIf="visible"> <h1>Hello {{name}}!</h1></div>`, styles: [`h1 { fo ...

Is there an alternative course of action since determining if Observable is empty is not feasible?

I am diving into Angular 11 and exploring the world of Observables and Subjects as a beginner. Within my application, I have a mat-autocomplete component that organizes its results into categories. One of these categories is dedicated to articles, and I&a ...

What are the benefits of using material-ui@next without the need for

Thinking about creating a project using material-ui@next, but trying to avoid using withStyles. However, encountering issues with the draft of TypeScript that includes the decorator @withStyles. This leads to one question - is it possible to use material ...

React Query successfully retrieves the path, but unfortunately fails to render the image in the display

Currently facing an issue where I am trying to retrieve images from the backend using ReactQuery. Here is the ReactQuery code snippet: export const useGetProductImagesByProductId = (productId: string) => useQuery({ queryKey: ['productIm ...

Checking the parameters passed to a function in Typescript: A step-by-step guide

Currently, I am working with Typescript and then transpiling my TS code into JavaScript. However, I have encountered an issue that I am struggling to resolve. The error message I am facing is as follows: Error Found in TypeScript on Line:2 - error TS230 ...

In the production build, the RegEx validation is lacking and fails to accept certain characters like 0, 2, 7, a, c, u, x, and occasionally z

Incorporating Angular 15.2.10 and Typescript 4.9.5, the RegEx utilized in one of my libraries and exposed via a service is outlined as follows: private readonly _DISALLOWED_CHARS_REGEX_GENERAL = new RegExp(/^[^\\/\?\!\&\: ...

Using Mongoose $addToSet to add items to an array only if they are unique

Currently, my code is set up to add new flagDtos using $addToSet without consideration for the uniqueness of item.name. However, I want to change this behavior so that: If item.name is unique, add the new flagDtos object. Otherwise, update the existing fl ...

The unit test is running successfully on the local environment, but it is failing on Jenkins with the error code TS2339, stating that the property 'toBeTruthy' is not recognized on the type 'Assertion'

I've been tackling a project in Angular and recently encountered an issue. Running 'npm run test' locally shows that my tests are passing without any problems. it('should create', () => { expect(component).toBeTruthy();}); How ...

What is the reason for the lack of overlap between types in an enum?

I'm having trouble understanding why TypeScript is indicating that my condition will always be false. This is because there is no type overlap between Action.UP | Action.DOWN and Action.LEFT in this specific scenario. You can view the code snippet and ...