Ensure that an Enum is limited to only numerical values (implement type checks for Enum)

I am looking to enforce a Generic type to be strictly a numerical enum. This means that the values of the Enum should only be numbers. Here is an example:

export type TNumberEnum<Enum> = { [key in keyof Enum]: number };

enum sample {
    AA,
    BB,
    CC = 'cc'
}

class SampleClass<CustomEnum extends TNumberEnum<CustomEnum>> {

    constructor( private value: CustomEnum ){}
    public sampleFunction(): CustomEnum {
        return this.value;
    }
}

let a = new SampleClass<sample>( sample.CC ); // Should fail since keyof sample has string value

// Could valueOf and toString cause any issues?

Check out a demo here

When passing a custom Enum to the SampleClass, I want to ensure that the Generic Enum is of a numerical enum type. Is this achievable?

Answer №1

When working with Typescript, it's important to note that type checks for the Enum type are not supported. One way around this limitation is to iterate over the enum elements and create a new object based on them. In JavaScript, an Enum is essentially transformed into an object.

For instance, if we take the example of an enum:

(function (example) {
    example[example["AA"] = 0] = "AA";
    example[example["BB"] = 1] = "BB";
    example["CC"] = "cc";
})(example || (example = {}));

Executing this code would result in:

{
  0:    "AA",
  "AA": 0,
  1:    "BB",
  "BB": 1,
  "cc": "CC",
  "CC": "cc"
}

However, when iterating over these properties, distinguishing between enum keys and values may not always be straightforward.

To address this issue, you can create a new "enum" by enforcing all enum values to be numeric using the following code snippet:

const myEnum = {}
for (let i = 0; i < keys.length; i++) {
    myEnum[i] = keys[i]
}

This approach helps in clearly defining the enum values as numeric indices.

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

Utilize VueJS to upload and visualize a file input on your website

I am currently working with TypeScript and Haml in conjunction with vue.js. My goal is to enable users to upload and view a file seamlessly using the vue.js framework. I have successfully managed to upload an image, however, I am facing an issue where the ...

Experiencing an issue with my Angular 6.1.0 setup, using angular-cli 7 and primeng 7 - specifically encountering the error message "Initializers are not allowed in ambient context."

Issue encountered in the primeng package: While examining node_modules/primeng/components/picklist/picklist.d.ts, errors were found at line numbers 65 and 66. I have investigated the primeng package further. primeng/components/picklist/picklist.d.ts l ...

Is the ng-selector in Angular2 not sorting items alphabetically as expected?

This code snippet demonstrates the use of ng-selector in an .html file <ng-selector name="company" [(ngModel)]="company_selected" [formControl]="loanApplyForm.controls['company']" ...

Opening a modal in Angular2+ when selecting an item from ngx-chips (tag-input)

I need to implement a functionality where clicking on a tag in a dropdown should trigger the opening of a modal window in my Angular application. Below is the code snippet related to this feature: <div class="force-to-the-bottom"> <tag-input [ ...

Typescript causing undefined React Router match issue

Currently, I am working on a basic eCommerce Proof of Concept using react and TypeScript. Unfortunately, I am facing an issue where I am unable to pass props to a product detail page or access the match containing the params. This is how my Routes pages a ...

Navigating through Angular to access a component and establishing a data binding

I am looking for the best way to transition from one component to another while passing data along with it. Below is an example of how I currently achieve this: this.router.navigate(['some-component', { name: 'Some Name' }]); In Some ...

typescript page objects in protractor are showing an undefined property

Hey there, I'm facing an issue while using POM in Protractor with TypeScript in Angular CLI. The error I'm encountering is "Cannot read property 'sendUsername' of undefined". Since I'm new to TypeScript, can someone guide me on how ...

Error in Typescript resulting from conditional rendering with props

Consider this straightforward conditional statement with a component return: let content = movies.length > 0 ? movies.map((movie, i) => <MovieCard key={i} movie={movie} />) : null; Upon running Typescript, an error regarding the 'movie&a ...

The key is not applicable for indexing the type as expected

Here is the TS code I am working with: type Fruit = { kind: "apple" } | { kind: "grape"; color: "green" | "black" }; type FruitTaste<TFruit extends Fruit> = TFruit["kind"] extends "apple" ? "good" : TFruit["color"] extends "green" ? "good" : ...

The angular framework is unable to assign a value to the property 'xxxx' because it is currently undefined

I am currently working on a simple application using Ionic (angular) and I am facing an issue with the error message: Cannot set property 'origin' of undefined Below is the interface for Product.ts: export interface Products{ id: number ...

Incorrect date generated by Moment.js from Unix timestamp

Is there a way to store unixtime as a Moment.moment state? Using moment(timestamp) seems to provide a different date. const [date, setDate] = useState<moment.Moment | null>(null); const timestamp = Math.floor(date.getTime() / 1000); setDate(m ...

Difficulty accessing class functions from the test application in Node.js NPM and Typescript

I created an NPM package to easily reuse a class. The package installs correctly and I can load the class, but unfortunately I am unable to access functions within the class. My project is built using TypeScript which compiles into a JavaScript class: For ...

Jest is raising a TypeError: Unable to access attributes of an object that is undefined (referencing 'getVideoTracks')

When running my unit tests with Jest, I encountered an error: TypeError: Cannot read properties of undefined (reading 'getVideoTracks') Does anyone have any suggestions on how to properly test the following line using Jest? [videoTrack] = (await ...

Having difficulty implementing dynamic contentEditable for inline editing in Angular 2+

Here I am facing an issue. Below is my JSON data: data = [{ 'id':1,'name': 'mr.x', },{ 'id':2,'name': 'mr.y', },{ 'id':3,'name': 'mr.z', },{ & ...

Typescript struggling to load the hefty json file

Currently, I am attempting to load a JSON file within my program. Here's the code snippet that I have used: seed.d.ts: declare module "*.json" { const value: any; export default value; } dataset.ts: import * as data from "./my.json" ...

Expanding the typings for an established component in DefinitelyTyped

Is there a way to define new typings for additional props in DefinitelyTyped? After updating the material-ui library with some new props for the SelectField component, I realized that the typings in DefinitelyTyped are outdated. Is it possible to extend th ...

Structure of document

Could anyone clarify for me the meaning of (callback[, thisObject]); that is mentioned in the TypeScript documentation here? I am particularly curious about the brackets themselves [, ]. ...

Is there a way to customize a chart in Ionic 2 to resemble the image provided?

Hello there, I am currently using import {Chart} from 'chart.js'; to generate my chart; however, I am facing some difficulties. My goal is to create a chart similar to the one displayed below. Warm regards //Generating the doughnut this.dou ...

Modify one specific variable within my comprehensive collection on Firebase Firestore

After clicking the button, I need to update a variable. The variable in question is "bagAmount" and it is stored in my firestore collection. Here is a link to view the Firestore Collection: Firestore Collection Currently, I am able to update one of the va ...

Struggling to successfully pass React props.children

Currently, I am utilizing react in my project and I have encountered an error when passing props.children to the Header component. Despite passing React as the type, the following error message is displayed. I am unsure why this error is happening. e ...