Reputation: 671
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 ?
Upvotes: 0
Views: 48
Reputation: 12025
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.
Upvotes: 1