0

I have created a enum in typescript:

export enum ProductType {
  FRUIT,
  CLOTH,
}

I wonder if I receive string value fruit and cloth, how can I convert the string to the enum type. Here is what I tried:

const value: string = 'fruit';

// compiler error: Element implicitly has an 'any' type because index expression is not of type 'number'
const productType: ProductType = ProductType[value.toUpperCase()];

But I get compiler error pointing to ProductType[value.toUpperCase()]:

Element implicitly has an 'any' type because index expression is not of type 'number'

What is the right way to convert string to enum type in typescript?

user842225
  • 5,445
  • 15
  • 69
  • 119
  • Hey, have you tried this solution ? https://stackoverflow.com/a/56076148/8763644. I would also consider erasing const and using **var** instead. – ahmet gül Aug 04 '22 at 13:48
  • 1
    Is the goal that the compiler should *know* that the value is literally `"fruit"` and that therefore the uppercase version is `"FRUIT"` and a known key of `ProductType`? That is, if you wrote `"froot"` accidentally, you'd want a compiler error? If so then you could possibly do [this](https://tsplay.dev/mZ4pew), but this seems like an odd thing to do. If that *is* what you want then I could write up an answer explaining it. If it is *not*, could you clarify more, possibly with some other examples? – jcalz Aug 04 '22 at 13:52
  • @ahmetgül `var` is a thing of the past ;) –  Aug 04 '22 at 14:15
  • Hey @MikeS., thanks for the information. Actually, I know that var is kind of a code smell. However, for the current topic, when I found some working examples and they all used "var". In addition to that, I saw that a user comment an answer to imply similar to that "did not work with const enum and worked with var". That's why I typed it at the end. If you have a different solution, I would love to learn :) – ahmet gül Aug 04 '22 at 14:24
  • @ahmetgül Fair enough ;) The Question you linked seems to be an almost exact duplicate, so I marked it as such. –  Aug 04 '22 at 14:27
  • Thanks, I used the solution from @ahmetgül's link. It works. – user842225 Aug 04 '22 at 15:34

0 Answers0