When looking at the code snippet below, I encountered an issue with discriminating 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 // The argument is still of the union type and not narrowed down
} else {
return arg // Same situation here
}
}
However, if the status
property is changed to a literal type, then it becomes possible to discriminate the union.
function f(arg: { status: "one"; one: boolean } | { status: "two"; two: boolean }) {
if (arg.status=== "one") {
return arg // Now arg is of type { status: "one"; one: boolean }
} else {
return arg // And here it's of type { status: "two"; two: boolean }
}
}
So, the question arises as to why it doesn't work in the first case. Is it because discriminated unions only function with literal types or could there be another reason?
I attempted to search through the documentation to see if it mentions anywhere that discriminated unions are exclusive to literal types, but I couldn't find any information on this.