Reputation: 4860
I have a typescript enum myEnum
(with string values) and a function foo
returning a string.
I need to convert return value of foo
to myEnum
and default on some value if key is not present in enum.
Let's condider this piece of code:
enum myEnum {
none = "none",
a = "a",
b = "b"
}
function foo(): string {
return "random-string";
}
function bar(): myEnum {
const t = foo();
if(t in myEnum) {
return myEnum[t];
}
return myEnum.none;
}
console.log(bar());
That fails with typescript 4.1.2 with error
Element implicitly has an 'any' type because expression of type 'string' can't be used to index > type 'typeof myEnum'. No index signature with a parameter of type 'string' was found on type 'typeof myEnum'
How should I do that without losing typesafety ?
Upvotes: 0
Views: 363
Reputation: 3823
You can try to suppress this warning using type guard
enum myEnum {
none = "none",
a = "a",
b = "b"
}
function foo(): string {
return "random-string";
}
function isMyEnum(s: string): s is myEnum {
return s in myEnum;
}
function bar(): myEnum {
const t = foo();
if(isMyEnum(t)) {
return myEnum[t];
}
return myEnum.none;
}
console.log(bar());
Upvotes: 0
Reputation: 120498
t
is a string
, in no-way related to the set of values in your enum
.
Inherently you need to lose some type-safety, because the string could be any value. As such, you must cast it to a myEnum
key for the win:
const t = foo() as keyof typeof myEnum;
Upvotes: 1