Using a Typescript enum as a parameter type can lead to accepting incorrect values

When working with TypeScript, I have defined an enum, and now I want to create a function that accepts a parameter whose value is one of the enum's values. However, TypeScript does not validate the value against the enum, allowing values outside of the specified range to be passed. Is there a way to enforce this validation?

Example

enum myenum {
    hello = 1,
    world = 2,
}

const myfunc = (num:myenum):void => console.log(`num=${num}`);

myfunc(1);            // num=1 (expected)
myfunc(myenum.hello); // num=1 (expected)

//THE ISSUE: I'm expecting next line to be a TS compile error, but it is not
myfunc(7); // num=7

Alternative

If I use a type instead of an enum, I can achieve a similar outcome in terms of validation. However, by using a type, I may lose some of the additional functionality provided by enums.

type mytype = 1|2;
const myfunc = (num:mytype):void => console.log(`num=${num}`);

myfunc(1);
myfunc(7);  //TS Compile Error: Argument of type '7' is not assignable to a parameter of type 'mytype'

Answer №1

It seems like you may have high expectations for enums in TypeScript... :)

enum MyCoolEnum {
  A = 1,
  B = 2,
}

function test(data: MyCoolEnum) {
  console.log(`Test = ${typeof data}`)
}

test(1)
test(MyCoolEnum.A)
test(500)

When you run the code above, you'll notice that all lines print number, indicating that it's internally treated as a number and hence accepts any value. Enums are mainly a way to avoid using random numbers and enhance code readability.

However, if you switch from numeric values to string values for A and B, you'll encounter:

TSError: ⨯ Unable to compile TypeScript:
dima.ts:10:6 - error TS2345: Argument of type '1' is not assignable to parameter of type 'MyCoolEnum'.

10 test(1)
        ~
dima.ts:12:6 - error TS2345: Argument of type '500' is not assignable to parameter of type 'MyCoolEnum'.

12 test(500)
        ~~~

    at createTSError (/Users/odinn/.nvm/versions/node/v10.15.1/lib/node_modules/ts-node/src/index.ts:423:12)
    at reportTSError (/Users/odinn/.nvm/versions/node/v10.15.1/lib/node_modules/ts-node/src/index.ts:427:19)
    at getOutput (/Users/odinn/.nvm/versions/node/v10.15.1/lib/node_modules/ts-node/src/index.ts:554:36)
    at Object.compile (/Users/odinn/.nvm/versions/node/v10.15.1/lib/node_modules/ts-node/src/index.ts:760:32)
    at Module.m._compile (/Users/odinn/.nvm/versions/node/v10.15.1/lib/node_modules/ts-node/src/index.ts:839:43)
    at Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/Users/odinn/.nvm/versions/node/v10.15.1/lib/node_modules/ts-node/src/index.ts:842:12)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)

In summary, while numeric enums primarily serve as cosmetic enhancements representing numbers, switching to string enums enforces specific types matching.

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

Guide to retrieving specific information from a JSON file in an Angular application

Struggling with handling this JSON file [ [ { "category": "Bags", "productData": [ { "id": 1000, "name": "Tro ...

What is the best way to incorporate node_module during the iOS build process in Ionic 2?

Looking to implement an autosize module for automatic resizing of an ion-textarea. Module: Following the installation instructions, I tested it in the browser (ionic serve) and on my iPhone (ionic build ios => run with xcode). Browser: The module wor ...

How can one determine if a background image has successfully loaded in an Angular application?

In my Angular 7 application, I am displaying a background image in a div. However, there are instances when the link to the image is broken. The way I bind the image in my HTML is as follows: <div [ngStyle]="{'background-image': 'url(&a ...

The type 'myInterface' cannot be assigned to the type 'NgIterable<any> | null | undefined' in Angular

I am facing an issue that is causing confusion for me. I have a JSON data and I created an interface for it, but when I try to iterate through it, I encounter an error in my HTML. The structure of the JSON file seems quite complex to me. Thank you for yo ...

Universal categories, limitations, and hereditary traits

As a newcomer to Typescript and generics, I am unsure if I have encountered a bug/limitation of Typescript or if I am missing the correct approach to achieve my desired outcome. I have a base class called Widget which is generic and holds a value of type ...

Experiencing compatibility issues with NextAuth and Prisma on Netlify when using NextJS 14

While the website is functioning correctly on development and production modes, I am encountering issues when testing it on my local machine. After deploying to Netlify, the website fails to work as expected. [There are errors being displayed in the conso ...

Click on the div in Ionic 2 to send a variable

<div class="copkutusu" (click)="kanalsil(kanalid,deneme)" #kanalid id={{ver.channelid}} #deneme id={{ver.channelapikey}}></div> I am requesting kanalid.id and deneme.id in my .ts file. Even though they are the same variable names, they repres ...

Enhance Express Middleware with Typescript for advanced functionality

Currently in the process of developing a REST API using Express and Typescript, I am encountering difficulties when trying to extend the Request/Response objects of Express. Although my IDE shows no errors, Typescript throws TS2339 Errors during compilati ...

I love the idea of the music playing on as I navigate between pages or tabs. Such a cool feature with Next

I'm looking to implement a music player within my next.js application. How can I ensure that the currently playing track doesn't stop when switching between pages? Essentially, I want the music playback to continue seamlessly as users navigate th ...

What is the best way to execute an Nx executor function using Node.js?

Can a customized Nx executor function be executed after the app image is built? This is the approach I am taking: "migrate-up": { "executor": "@nx-mongo-migrate/mongo-migrate:up", "options": { &q ...

The latest update of WebStorm in 2016.3 has brought to light an error related to the experimental support for decorators, which may undergo changes in forthcoming

Hello, I recently updated to the latest WebStorm version and encountered this error message: Error:(52, 14) TS1219:Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' ...

typescript error: passing an 'any' type argument to a 'never' type parameter is not allowed

Encountering an error with newUser this.userObj.assigned_to.push(newUser);, receiving argument of type 'any' is not assignable to parameter of type 'never' typescript solution Looking for a way to declare newUser to resolve the error. ...

Display a popup notification when clicking in Angular 2

Can anyone help me with displaying a popup message when I click on the select button that says "you have selected this event"? I am using Angular 2. <button type="button" class="button event-buttons" [disabled]="!owned" style=""(click)="eventSet()"&g ...

Guide on transforming an array of objects into a fresh array

I currently have this array: const initialData = [ { day: 1, values: [ { name: 'Roger', score: 90, }, { name: 'Kevin', score: 88, }, { name: 'Steve&apo ...

I am verifying the user's login status and directing them to the login page if they are not already logged in

My goal is to utilize ionViewWillEnter in order to verify if the user is logged in. If the check returns false, I want to direct them to the login page and then proceed with the initializeapp function. My experience with Angular and Ionic is still limite ...

Running a TypeScript file on Heroku Scheduler - A step-by-step guide

I have set up a TypeScript server on Heroku and am attempting to schedule a recurring job to run hourly. The application itself functions smoothly and serves all the necessary data, but I encounter failures when trying to execute a job using "Heroku Schedu ...

What sets apart the two methods of defining an event in a React component?

Can you explain the nuances between these two approaches to declaring events in a React component? Is it merely a matter of personal preference, or are there more subtle distinctions between them? interface PropsX { onClick: () => void; } const But ...

Can someone please explain how to bring in the Sidebar component?

click here for image description check out this image info An issue arises as the module '@components/Sidebar' or its type declarations cannot be located.ts(2307) Various attempts were made, including: import Sidebar from '@components/Sid ...

What is the best way to programmatically generate a service within Angular?

Is there a way to dynamically create services at runtime using a string name (like reflection)? For example: let myService = new window[myClassName](myParams); Alternatively, you could try: let myService = Object.create(window[myClassName].prototype); m ...

Saving a user with a BLOB avatar in Angular 5: Tips and Tricks for Success

As a newcomer to Angular, I am trying to figure out how to properly save a new user with an avatar. Can someone help me understand how to pass the Blob value of the avatar to my user Model for successful saving? Below is the code snippet I am working with ...