Retrieving an Enum member based on its value in TypeScript

I am working with an enum called ABC:

enum ABC {
A = 'a',
B = 'b',
C = 'c',
}

In addition, I have a method named doSomething:

doSomething(enum: ABC) {
  switch(enum) {
    case A : 
      console.log(A);
      break;
    case B : 
      console.log(B);
      break;
    case C : 
      console.log(C);
      break;
  }
}

I am wondering if it is possible to invoke the method doSomething(enum: ABC) using strings like 'a', 'b', 'c.

For example, I would like to achieve something similar to this:

const enumA: ABC = ABC.getByValue('a'); // this would be equivalent to ABC.A
doSomething(enumA);

Is this type of functionality achievable in TypeScript?

Answer №1

Typescript focuses on ensuring type safety during compilation. Therefore, there is no need to use ABC.getByValue('a') in this case, as the value 'a' is already known and suitable for the function. In situations where there are no better options, Typescript can be "tricked" into accepting seemingly incorrect types using 'as':

doSomething('a' as ABC);

An alternative approach to enums is to define the type explicitly:

type ABC = 'a' | 'b' | 'c';

This way, the correct strings are enforced, allowing direct passing of 'a'.

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

How can I enable a button in a React application when the text input is not populating

For my Instagram MERN project, I have implemented a Comment box feature for users. The Post button starts off disabled and becomes enabled when text is entered. However, despite entering text, the button remains disabled, preventing submission. Below is th ...

Is it possible to use different names for the parameters in a function while still maintaining the same

(Apologies for any language barriers!) It's difficult to articulate my thoughts in English, but here is the code I've written: function calculateAge(yearBorn){ return 2020 - yearBorn; } var johnAge = calculateAge(1990); var janeAge = calcul ...

I am looking for a sample code for Tizen that allows scrolling of a <div> element using the bezel

Seeking a functional web application in Tizen that can scroll a div using the rotating bezel mechanism. I have dedicated several hours to getting it to work without success. I keep revisiting the same resources for the past three days: View Link 1 View Li ...

Troubleshooting issues with jQuery `.live()` event not triggering as expected

In a project I am working on, I have implemented complex AJAX functionality to fetch inner page content from a WordPress blog. Due to the dynamic nature of the site, where the DOM is replaced after page load via AJAX, I have opted to use jQuery's .liv ...

What are the steps to enable ajax communication with a database for posting, retrieving, and removing data?

Is there a way to utilize ajax for posting, deleting, and getting data from a database? I am looking to post content and then be able to delete it through the following link: (this is part of an assignment) However, I must use /ajax/addrecord.php and /a ...

Seamless Axios operations even without internet connection in Vue.js

In my Nativescript Vue.js application, there is a functionality where the user clicks on login, Axios makes a call to an endpoint to fetch a token. However, I noticed that when the emulator phone is offline, the Axios call still goes through and the &apos ...

The JSX Configuration in TypeScript: Comparing ReactJSX and React

When working with Typescript and React, it's necessary to specify the jsx option in the compilerOptions section of the tsconfig.json file. Available values for this option include preserve, react, react-native, and react-jsx. { "compilerOptions": { ...

Adjust the badge's color based on the status retrieved from the jQuery AJAX call

I've been working on retrieving data from an endpoint through a get request, and I'm looking to adjust the color of the request status based on the response. $.ajax({ type: 'GET', url: 'api/v1/service/tax', succe ...

What might be causing AngularJS to fail to display values when using TypeScript?

I have designed the layout for my introduction page in a file called introduction.html. <div ng-controller="IntroductionCtrl"> <h1>{{hello}}</h1> <h2>{{title}}</h2> </div> The controller responsible for handling th ...

Error encountered: Unknown token '<' and Loading chunk 16 unsuccessful

Having a react app created with create-react-app, I encounter errors whenever I deploy to netlify and there is a new build. Uncaught SyntaxError: Unexpected token '<' 16.0fcd6807.chunk.js:1 Immediately after this error, another one pops up: ...

Retrieve the ID of the image element using Jquery from a collection of images within a div container

I'm encountering a simple issue that I can't seem to solve. I am working on a basic slider/gallery with the following functionalities: 1) "If button 1 is clicked, image one will appear." 2) "Clicking on button 2 will make IMAGE 1 slide left and I ...

How can I set the background of specific text selected from a textarea to a div element?

Is it possible to apply a background color to specific selected text from a Text area and display it within a div? let elem = document.getElementById("askQuestionDescription"); let start = elem.value.substring(0, elem.selectionStart); let selection = ...

Is there a way to access the sqlite3 database file in electron during production?

Currently, I have an electron application that I developed using the create-electron-app package. Inside the public folder of my Electron app, both the main process file and the sqlite3 database are located. During development, I can access the database ...

Extracting Data from JSON Structures

I am struggling with extracting data from a JSON string that looks like this: var txt= '{“group”: [ {“family1”: { “firstname”:”child1”, “secondname”:”chlid2” }}, {“family2”: { ...

Is there a way to achieve a transparent background while animating the second text?

I am seeking to create a unique typography animation that involves animating the second text, which is colored and consists of multiple text elements to animate. The animation should showcase each text element appearing and disappearing one after the other ...

Harnessing the power of flexbox for data visualization

Trying to use flexbox to display data from a dataset in my code. Here is the code snippet: <div ng-app="myapp" ng-controller="FirstCtrl"> <div ng-repeat="name in names" class="graph-wrapper"> <div class="aside-1 content"> ...

Should we enable client-side validation and unobtrusive JavaScript in the Web.config file?

I'm currently working on an ASP MVC application, where all form and UI code is written in AngularJS for validation purposes. I didn't use any HTML helpers. Do I need to include the entries ClientValidationEnabled and UnobtrusiveJavaScriptEnabled ...

What is the best way to refresh an Angular model containing nested data?

This week, I started working on a proof of concept with Angular Material where I have a table displaying nested data: <table> <thead> <tr> <th colspan="2">Employee Name</th> <th>Ovr&l ...

Disabling an image is similar to deactivating a button

document.getElementById("buttonName").disabled = true; I have successfully disabled a button using the code above. However, I am now facing a challenge with using pictures as buttons that have an onClick function. Is there a way to disable the onClick fun ...

What is the reason that certain functionalities do not work on an element that has two CSS classes assigned to it

I have a unique situation with two input elements and a button: <input class="close-acc-usr opt-in" type="text" name="closeAccUsr" /> <input class="close-acc-pin opt-in" type="number" name="cl ...