0

I have the following enum :

enum ABC {
A = 'a',
B = 'b',
C = 'c',
}

I have the folloging method :

doSomething(enum: ABC) {
  switch(enum) {
    case A : 
      console.log(A);
      break;
    case B : 
      console.log(B);
      break;
    case C : 
      console.log(C);
      break;
  }
}

is it possible to call the method doSomething(enum: ABC) with one of the following strings : 'a', 'b', 'c'. What I would like to do would be something like :

const enumA: ABC = ABC.getByValue('a'); // this would be like ABC.A
doSomething(enumA);

Is it something like this possible in typescript ?

1
  • 1
    It's not reverse mapping here. Commented Apr 15, 2021 at 23:41

1 Answer 1

1

Typescript is about enforcing type safety at compile-time only. So there's no need for ABC.getByValue('a') here, since you know the value is 'a' and is OK for the function. In cases like this, where there's no better alternative you can "force" Typescript to swallow the ostensibly wrong type with 'as':

doSomething('a' as ABC);

Another simpler possibility than enums is to set the type like this:

type ABC = 'a' | 'b' | 'c';

Then the correct strings are enforced, and you can pass in 'a' directly.

Sign up to request clarification or add additional context in comments.

1 Comment

Never thought using the type as an enum, but it is the best way to do what i want actually. Thanks for that !!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.