0

I have defined a string-based enum. What is the idiomatic way to obtain type safe enum objects out of untyped strings?

E.g. what should I do in the following:

enum Car {
    BMW = 'bmw',
    AUDI = 'audi'
}

const car = 'bmw';
const typedCar: Car = // ??

The suggested way of doing a:

const typedCar: Car = Car[car];

(as suggested e.g. in this answer) does not work for String Enums AFAICT.

Marcus Junius Brutus
  • 26,087
  • 41
  • 189
  • 331
  • You can use `as` keyword to tell TS `car` type `const typedCar = car as Car;` – Nikita Madeev Aug 31 '20 at 13:08
  • 1
    Does this answer your question? [Getting the enum key with the value string (reverse mapping) in TypeScript](https://stackoverflow.com/questions/54297376/getting-the-enum-key-with-the-value-string-reverse-mapping-in-typescript) – Roberto Zvjerković Aug 31 '20 at 13:12
  • @ritaj The presently accepted answer to that question (https://stackoverflow.com/a/54297863/274677) does not type check and if one edits it to type check assertions are still needed so it is not clear to me why it is superior to the much simpler: https://stackoverflow.com/a/63671601/274677 – Marcus Junius Brutus Aug 31 '20 at 13:39

1 Answers1

1

I would assert that it is a car by using the as keyword.

The code would be const typedCar = car as Car;

Robert Kossendey
  • 6,733
  • 2
  • 12
  • 42