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 ?