"Utilize an enumeration to access a certain number by passing

Seeking to retrieve the id based on the animal's name:

enum Animals {
  Cat = 1,
  Dog,  // 2
}

const name: string = "Cat";

const id: number = Animals[name] // Element implicitly has an 'any' type because index expression is not of type 'number'.

Cited from https://basarat.gitbooks.io/typescript/docs/enums.html#enums-and-strings

enum Tristate {
  False,
  True,
  Unknown
}

console.log(Tristate["False"]); // 0

Issue - How can I obtain 1 linked with Cat

Answer №1

When utilizing a variable (for instance, category) to reference the value for an enumeration, if you specify the type as text, it assumes it could potentially contain any value, even ones that don't exist in the enum. Consequently, the result will display as whatever.

To circumvent this problem, you have the option of either directly invoking the enum (Cars['SUV']) or constraining the values of your variable to match the enum's values like so:

const category: 'Red' | 'Blue' = 'Red';
const quantity: number = Cars[category]; // 3

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

Tips for Creating and Verifying JWE in Node.js

I attempted to use the following code in order to create an RSA-OAEP and A128GCM JWE generator and validator. It successfully encrypts claims and generates the JWE, then decrypts it and provides me with the original claims when running on node.js. However, ...

Tips for incorporating animation while altering element styles within JavaScript

I am looking to incorporate a sliding animation that moves the element downward when the display property is set to block, and upward when it's set to none or an empty string, here is the current JavaScript code I have: <script> function showQ ...

The header of the table does not extend to fill the entire width of the

Greetings! I have a table below that is not extending to the full width of the page. I suspect it has to do with my code snippet: <div style={{ overflow: 'auto', height: '250px' }}> But, I specifically want the table headers t ...

Can I update a label using ajax from the controller?

Hello everyone, I am facing a challenge in changing the text label coming from my Controller's JsonResult. There are two specific issues that I am encountering: 1) I am having difficulty displaying the text sent from my controller onto my view... ...

Refresh the HTML page following a jquery click event

One of my onclick functions is designed to return sorted data in a specific format when triggered. Here's the code snippet for this function: $(document).ready(function () { $(".feedbackClick").click(function () { $.post("/Analyze/GetSorte ...

Can you explain the inner workings of the provided code in a step-by-step manner?

I stumbled upon this code snippet that checks if the number of occurrences of an element in an array is greater than a specified value, and if so, it will remove the number: function deleteNth(arr,x) { var cache = {}; return arr.filter(function(n) { ...

Animating the change in Slider value with Material-UI in React

Recently delving into React, I encountered my first challenge that has been consuming my time for hours. I'm working with a Slider component from Material-UI and seeking to animate the value changes. Currently, when clicking on a button, the slider i ...

Using Nuxt: Integrating a Third-Party Library into a Vue Page Component

Consider the scenario where you wish to integrate a third-party JavaScript library (such as Three.js) into a Vue page using Nuxt. Attempting to link local sources in the head section of either nuxt.config.js or YourPage.vue proves unsuccessful: head: { ...

updating Chart.js to dynamically draw a line chart with updated dataset

Is there a way to pass back the retrieved value into the dataset data without it returning empty? It seems that the var durationChartData is empty because the array is initialized that way. How can I update it to display the correct values after receiving ...

Learn how to display data from the console onto an HTML page using Angular 2

I am working on a page with 2 tabs. One tab is for displaying active messages and the other one is for closed messages. If the data active value is true, the active messages section in HTML should be populated accordingly. If the data active is false, th ...

Placing a component within a .jsx file instead of utilizing a .css file for positioning

Seeking a way to position a component within a .jsx-file, rather than a .css-file, to accommodate multiple instances of the same component performing various tasks on different parts of the page. Avoiding duplication of files with minor CSS class changes, ...

The function document.getElementById(...) is failing to retrieve the text data from the table as expected

Greetings fellow HTML and JavaScript novice! I've got a table with input cells in the bottom row: <table class="convtbl" id="table1"> <tr> <td>Distance 1 (in miles)</td> <td>Time ...

What strategies can be utilized to condense code when needing to adjust a className based on various props?

I am looking to condense this code, particularly the [if~else if] block, in order to dynamically change a className based on different props passed. export default function Button(props) { const { name, height, color, bgColor } = props; let className = ...

Is it possible for the client to prevent the blocking of the Cross-Origin Resource Sharing (CORS) error?

I am encountering an issue with my web app that involves CORS operations when making $.getJSON AJAX calls. Typically, this functions properly on most client browsers due to the server having CORS enabled. However, I recently discovered that when using IE 1 ...

Discovering the position of points on a plane following a rotation within Aframe

Currently, I am utilizing Aframe to create a plane within a virtual scene. My goal is to determine the central points on all 4 sides of the plane based on its xyz rotation. Is there any specific equation or function within Threejs or Aframe that can assis ...

Remove underscores from a project utilizing browserify

I am currently working on a npm project and trying to ensure it is browser-compatible with browserify. One of the dependencies in this project is underscore. In order to build the project using browserify without including underscore in the final file, I h ...

Is there a way to establish the starting content/value for this tinymce editor?

I have integrated tinymce editor from this repository into my application: https://github.com/dyonir/vue-tinymce-editor. My goal is to pre-populate the editor with content upon initialization. Although I attempted using v-model, it did not work as expect ...

What is preventing the use of data post submission in React JS?

After posting data to the navigation, I retrieve it and then use the following code: .then(data => console.log(data.PathPDF)) .then(data => window.open(data.PathPDF, '_blank', 'noopener,noreferrer')); While I can successfully ret ...

Adding items from the JSON data to a nested array at index i

In my project, I am working with two files: index.js and list.json. My goal is to extract an element from list.json and insert it into a nested array following the structure [hour][visits per hour]. The hour refers to the index of the hour; for example, ...

Executing asynchronous JavaScript code within a Golang request: a comprehensive guide

I am in need of a solution to retrieve the content from dynamically generated pages using ajax on a website, specifically with code written in golang. I have found examples for non-ajax pages but struggling to find one that works for ajax pages. Any guid ...