0

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 ?

2

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

great ! Typescript has quite evolved since version 0.8 apparently :)
0

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.