When using Typescript 2.2.2 (with the strictNullChecks
option set to true), I encountered an unexpected behavior. Is this a bug or intentional?
interface Fn {
(value: any): number;
}
var example1: Fn = function(value) {
if (value === -1) {
return undefined; // No error, although I was expecting one
}
return value;
};
var example2 = function(value: any): number {
if (value === -1) {
return undefined; // Throws errors as expected
}
return value;
};
I noticed that example1
does not produce an error because the function return type is inferred as any | undefined
. This type is then compared to the contextual typing of Fn
, which is number
, and thus found to be compatible. I had anticipated the return type of the function to be determined by the contextual typing rather than compared against it. Is there a way to enforce this without requiring the consumer of Fn
to also explicitly type the function return?
This brings up the point that interfaces only provide contracts that must be followed, rather than dictating implementation details such as return types.
Additionally, when the parameter type (number
) causes the inferred return type (number | undefined
) to be incompatible with the contextual type (from Fn2
, namely number
), the error is caught:
interface Fn2 {
(value: number): number;
}
// `example3` throws an error since the inferred function return type is `number | undefined`, which doesn't match the expected `number` return type.
var example3: Fn2 = function(value) {
if (value === -1) {
return undefined;
}
return value;
};