In the snippet below, I'm not able to discriminate the union type using the typeof operator.
function f(arg: { status: number; one: boolean } | { status: string; two: boolean }) {
if (typeof arg.status === "number") {
return arg // arg is still of the union type and is not narrowed
} else {
return arg // similar here
}
}
But if status is changed to some literal type, then the union can be discriminated.
function f(arg: { status: "one"; one: boolean } | { status: "two"; two: boolean }) {
if (arg.status=== "one") {
return arg // here arg is of type { status: "one"; one: boolean }
} else {
return arg // and here it's of type { status: "two"; two: boolean }
}
}
So, I wanted to know why does it not work in the first case, is it that discriminated unions only work with literal types or is there something else?
I tried to find in the docs to see if it's mentioned somewhere that discriminated unions only work with literal types but I couldn't find anything.