Here is some TypeScript code that I am working with:
type NumberOrNever<T> = T extends number ? T : never
function f<T>(o: T) : NumberOrNever<T> {
if (typeof o === "number") return o;
throw "Not a number!"
}
const b = f(4);
const c = f({});
When I try to compile this in the playground, it shows red lines under the return 0
statement and displays an error message saying
Type 'T & number' is not assignable to type 'NumberOrNever<T>'
. Can someone explain why this happens and suggest a solution?
Interestingly, the typescript playground correctly identifies that variable b will be a number and variable c will be of type never. However, it does not recognize that b will specifically be assigned the value 4. For example, consider the following code snippet:
function f<T>(o: T) : T {
if (typeof o === "number") return o;
throw "Not a number!"
}
const b = f(4);
In this case, b is properly typed as 4.