Unable to declare a string enum in TypeScript because string is not compatible

enum Animal {
    animal1 = 'animal1',
    animal2 = 'animal2',
    animal3 = 'animal3',
    animal4 = 'animal4',
    animal5 = 'animal5'
}
const species: Animal = 'animal' + num

Why does typescript give me an error when trying to assign a value to species? Even though num is a number, I specifically want to set predefined string values for this variable.

Type 'string' is not assignable to type 'Animal'.

Answer №1

It is important to ensure that the category specified is one of Cat, rather than the enum itself. This can be achieved by:

const cat = 4;
const category = Cat[`cat${cat}`] // Result: Cat.cat4

This approach provides type safety when attempting to access a number beyond the defined range. You can test this in the playground

enum Cat {
    cat1 = 'cat1',
    cat2 = 'cat2',
    cat3 = 'cat3',
    cat4 = 'cat4',
    cat5 = 'cat5'
}

const cat = 4;
const category = Cat[`cat${cat}`]

const cat6 = 6;
const category6 = Cat[`cat${cat6}`] // Error: Property 'cat6' does not exist on type 'typeof Cat'.

Answer №2

When working with Typescript, it's important to note that cat cannot be guaranteed to be just 1, 2, 3, 4, or 5 as it could also be something else entirely different. In order to handle this uncertainty, you must explicitly specify to Typescript that you are confident it will be of type Cat.

The main issue arises when trying to concatenate 'cat' + someVar and assign it to type Cat, which the compiler does not allow.

It is crucial to exercise caution when employing this method, as essentially overriding the compiler's error means you must guarantee beforehand that what you're dealing with will consistently be a valid cat.

enum Cat {
  cat1 = 'cat1',
  cat2 = 'cat2',
  cat3 = 'cat3',
  cat4 = 'cat4',
  cat5 = 'cat5',
}
const category: Cat = (('cat' + cat) as Cat);
enum Cat {
  cat1 = 'cat1',
  cat2 = 'cat2',
  cat3 = 'cat3',
  cat4 = 'cat4',
  cat5 = 'cat5',
}

// Using [Cat.cat1, Cat.cat2 ...] instead would be a safer approach.
// It's generally advised against using dynamic enum values like in this case.
for (const i of [1,2,3,4,5]) {
  const category: Cat = (('cat' + i) as Cat);
}

// The compiler would also allow this, but only because you've ensured that the type will always be of type Cat.
for (const i of ['dog']) {
  const category: Cat = (('cat' + i) as Cat);
}

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

First experience with Django Bootstrap Modal Ajax was flawless, but on the second attempt, it was not as successful

I am currently utilizing Django 2.2 in conjunction with Bootstrap. The method implemented is as follows: Triggering the opening of a modal window, User updates the data, User saves the data, Underlying table from where the window originated is updated a ...

Encountered an issue while trying to read properties of undefined (specifically 'meta') within a Vue 3 single-spa application

I've been working on a micro-frontend project, utilizing vue 3 and single-spa 5.9.3. Recently, I attempted to update one of the npm packages for a Micro-frontend to the latest release. The build process went smoothly, but it resulted in the following ...

Troubleshooting the Issue of PHP Variables Not Being Assigned to Javascript Variables

I am currently struggling with an issue. I am trying to assign a PHP value to a variable in Javascript. Here is what I have attempted: <script> JSvariable = <?php echo $PHPvariable; ?>; </script> However, this approach is not yieldi ...

Can a new EJS file be generated using the existing file as a template?

I am in the process of building a website navbar and I am curious about how to automatically inject code from one ejs file into another ejs file. In Python's Flask framework, this is accomplished using the principle of {% block title%} and in another ...

What is the best way to execute multiple Protractor test suites simultaneously?

Exploring Protractor for the first time. My goal is to run multiple test suites in a sequence. I have a complex angular form with various scenarios, each with its expected results. I want to execute all tests with just one command. Initially, I tried enter ...

Swapping out video files with varying quality using HTML5 and Jquery

Objective: Implementing a feature to change the video being played when a user clicks a button using Jquery. Example website for reference: (click on the "hd" button in the player control) More details: When the page loads, the browser will play the fi ...

Step-by-step guide on utilizing the material-ui AutoComplete feature to filter a table by selecting a key from a list and manually entering

I'm working on developing a filtering system similar to the AWS Dashboard, where users can select a filter key like instance state, which then displays the key in the input field and allows the user to enter a value to search for. I'm attempting ...

MVC5 Toggle Button for Instant Display and Concealment

I used to utilize this method in Web Form development by targeting the id and name of the input radio button. However, I am encountering difficulties implementing it in MVC5. Can someone kindly point out where I might be going wrong? Upon selecting a radi ...

Converting an rrule date value from an array to a customized string format

Here is an array that I am working with: [{ evening_feeding: false evening_feeding_time: "19:00" feeding_frequency_rule: **"FREQ=DAILY;INTERVAL=2"** id: 890 morning_feeding: true morning_feeding_time: "04:00 ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

Tips for showing and modifying value in SelectField component in React Native

At the moment, I have two select fields for Language and Currency. Both of these fields are populated dynamically with values, but now I need to update the selected value upon changing it and pressing a button that triggers an onClick function to update th ...

Having trouble with Array.filter functionality

Despite the multitude of discussions on this topic, I have not been successful in using the Array.filter method to remove an item from a string-based Array. Below is an example of the filter method being used in the context of mutating a Vuex store. UPDAT ...

Best practices for incorporating and leveraging node packages with Laravel Mix

As I embark on my Laravel (v 8.x) Mix project, I am encountering challenges when it comes to incorporating JavaScript from node modules. To kick things off, here is a snippet from my webpack.mix.js: mix.js('node_modules/mxgraph/javascript/mxClient.mi ...

Trying to use the `await` keyword results in a "SyntaxError: Unexpted identifier" message, even when used within an `async` function

Encountering an error with Javascript's await when using it inside an async module let ImagesArray = await getImages(); ^^^^^^^^^ SyntaxError: Unexpected identifier at createScript (vm.js:80:10) at Object.runInThis ...

Show blob file as a PDF document in a popup or dialog box using HTML and TypeScript

I am currently working on integrating TypeScript and HTML to showcase the result of a webservice call as a PDF in a popup/dialog within the same page. While I can successfully open the PDF in a new tab using the window.open(url) method, I'm encounter ...

What is preventing me from adding content to a <p> element?

I'm currently developing a ToDo list web application and I'm working on retrieving the information from 4 text boxes to create the content for each ToDo item. However, when I attempt to link the elements generated from the form, I encounter the ...

Updating the Scale of the Cursor Circle on my Portfolio Site

I attempted to find tutorials on creating a unique circle cursor that can hide the regular mouse cursor as well. After implementing it with a difference blend mode, I encountered an issue where I wanted the scale to change when hovering over a link. The ...

Steps to Remove the Displayed Image upon Click

I have a collection of images such as {A:[img1,img2], B:[img1]}. My goal is to remove the array values that correspond to previewed images upon clicking the delete button. Each image is equipped with its own delete button for this purpose. This snippet ...

What is the best method to assign the value of a useState variable to a specific field in an array of objects for inserting data in

**I have a billing form that includes product details for the admin to fill out. One field, labeled "BillID", should automatically populate with a default value of 'Bill ID + 1' through a variable. **Below is the code: const [BillIdFetch, setB ...

Implement a unique feature for specific days using jQuery UI Datepicker with a customized class

Looking to highlight a range of days horizontally in jQuery UI Datepicker with the multiselect plugin. To achieve this, I am utilizing the :before and :after pseudoelements of the a tags. .ui-state-highlight a:before, .ui-state-highlight a:after { con ...