Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to tell Typescript interpreter that variable will be a specific type in the runtime

I have a method that accepts argument of either string or MyEnum type and has a return type of only MyEnum. Also, there is a check – if a given argument is of MyEnum type, it will be returned immediately, otherwise additional logic is applied.

But when I want to do that I get this error:

Type ‘string | MyEnum’ is not assignable to type ‘MyEnum’.
Type ‘string’ is not assignable to type ‘MyEnum’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My code:

export enum MyEnum {
    Value1 = 1,
    Other = 10
}

export function TextToEnum(text: string | MyEnum): MyEnum {
    if (typeof text === typeof MyEnum)
        return text;

    switch (text) {
      case "val1":
        return MyEnum.Value1;
      default:
        return MyEnum.Other;
    }
}

>Solution :

Change your typeof check to use "number" instead of typeof MyEnum:

export function TextToEnum(text: string | MyEnum): MyEnum {
    if (typeof text === "number")
        return text;

    switch (text) {
      case "val1":
        return MyEnum.Value1;
      default:
        return MyEnum.Other;
    }
}

The reason why typeof MyEnum doesn’t work is because typeof always has the same string union type:

"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"

and therefore conveys no type information.

Playground


Alternatively, you can check if it isn’t a string:

export function TextToEnum(text: string | MyEnum): MyEnum {
    if (typeof text !== "string")
        return text;

    // ...
}

and it’ll also work.

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading