With typescript 2.5.2 the following code fails to compile with strictNullChecks
:
function ifnull<T>(x: T | null | undefined, def: T): T
{
return x != null ? x : def;
}
console.log(ifnull(2, 1));
giving the error:
Argument of type '2' is not assignable to parameter of type '1 | null | undefined'.
It seems it infers T to be 1
instead of number. When you compile without strictNullChecks it correctly infers the type number
. I am not confident enough to know if this is a bug in Typescript or expected behaviour, so I prefer to ask here before I fill a bug report.
Is this expected? what's the rationale of the strict inference, and is there a way to define ifnull
without having to call it as ifnull<number>(...)
or ifnull<string>(...)
?