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

I am looking to transfer information in CodeIgniter from a view utilizing AJAX post, handle that information in the controller, and then return the resultant array back to the view

I have been searching the entire internet, but unfortunately, I couldn't find a helpful solution. Any assistance would be greatly appreciated. Thank you in advance. MY HTML <div class="row"> I am unsure whether the form tag is required in my ...

The image slideshow on W3 Schools displays images in a stacked formation

Utilizing this code snippet from W3 Schools to incorporate an image slideshow into my web project. However, upon page load/reload, the images appear stacked vertically rather than horizontally (one above and one below). The slideshow functions properly aft ...

Using asynchronous functions in JavaScript to push an array does not function correctly

Trying to update the users array by pushing the dirs, but for some reason the dir property remains blank in the console.log statement after this. Any suggestions? I know I could use a synchronous function, but a friend mentioned that synchronous functions ...

Issue: Module "mongodb" could not be found when using webpack and typescript

I am encountering an issue while trying to use mongoose with webpack. Even though I have installed it as a dependency, when attempting to utilize the mongoose object and execute commands, it gives me an error stating that it cannot find the "." Module. Thi ...

Issues with Ionic 3 Directive Not Functioning

Struggling to create a custom directive in Ionic that won't resize automatically? I can't figure out what's going wrong. Here's the code snippet from my project, which is an Ionic 3 app with Angular 4: import { Directive, HostListener ...

Guidelines for utilizing basepath for specific pages in NextJS

I'm currently working on a NextJS application using version 13 and I have a question regarding setting the basepath for specific pages only. For example: "/auth/*" --> should not display the basepath "/remaining-pages" --& ...

What is the best way to utilize namespaces across multiple files in your program

I am currently working with TypeScript 1.6.2 and atom-typescript. In my project, I'm attempting to utilize namespaces across separate files: // Main.ts import * as _ from 'lodash' namespace Test { export var value = true } // Another.ts ...

Issues with React useState persisting new values between useEffect intervalsHere is a rephrased

I am attempting to store jokes and log a new value every time the interval runs (triggered by a get call) after 5 seconds. However, for some reason, the value is not rendering anything after each interval. I'm not certain if the jokes are actually bei ...

Utilizing imported components to set state in React

In my project, I created a functional component named Age and imported it into another functional component called Signup. This was done in order to dynamically display different divs on a single page based on the authentication status of the user. By sett ...

What is the best approach: Developing a class or a service to handle multiple interfaces?

My current project involves creating multiple interfaces, and I would like to keep them separate for clarity. Would it be wise to do this in a service or a class? Additionally, is it possible to utilize dependency injection for classes? Thank you for your ...

Here is a unique rewrite:"Adjusting the prop of a Material UI Button component depending on screen size breakpoints can be achieved by utilizing

While using the Material UI Button component, I encountered an issue with conditionally determining the variant of the button based on screen size. Specifically, I want the variant to be 'outlined' on medium and larger screens, and no variant at ...

Why does the header still show content-type as text/plain even after being set to application/json?

When using fetch() to send JSON data, my code looks like this: var data = { name: this.state.name, password: this.state.password } fetch('http://localhost:3001/register/paitent', { method: 'POST&a ...

In JavaScript, is it possible to dynamically alter and showcase the value of a select tag?

My code snippet in the HTML file contains Javascript: <script> $(document).ready(function(){ $("#sub").click(function(){ var user_issue = $("#issue").val(); ...

Error: Select dropdown placeholder malfunctioning

Even after trying numerous solutions from various forums, I am unable to make the placeholder display in my code. Maybe a fresh perspective can help spot what I might be missing. view image here I have experimented with using "" as the value, as ...

Issues with React Native imports not functioning properly following recent upgrade

Hey there, I’ve been tasked with updating an old React-Native iOS project from version 0.25.1 to 0.48.0. However, I’m encountering several compiler issues and struggling to navigate through the code updates. The project includes an index.ios.js file s ...

Download the ultimate HTML package with a built-in chart.js component directly from your nuxt app

I have a task to create a compact Nuxt application that produces a basic HTML file containing informative sections about the services offered to the clients of my organization. The main purpose is to generate an HTML file that can be easily downloaded and ...

Changing the content of a DOM element containing nested elements using JavaScript/jQuery

Need some help with a DOM element that looks like this: <span>text</span> <b>some more text</b> even more text here <div>maybe some text here</div> How can I replace text with candy to achieve this result: <span> ...

perform an action if any division element is void of content

Currently, I have a statement that checks if any of the Divs with the ID #Drop are empty. If one is found to be empty, an alert is shown. However, there seems to be an issue where the statement stops working when any div contains content. What I am trying ...

Problem with image title in jQuery mobile

My code seems to be having an issue where the title does not display completely when hovering over it. For example, if the title is set as "The Value", only "The" is shown and not "The Value". Can anyone help me identify the mistake? Thank you in advance ...

The functionality of RegExp is not as expected in this specific case, even though it works correctly in all

I am new to Node.js and currently transitioning from a PHP background, eager to learn more about it. My challenge involves using the following Regular Expression: /([A-Z]{2,})+/gim (identifying two or more consecutive letters). The string I am working w ...