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’.
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.
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.