Let's say we have a function that takes a value (for example, number
) and a callback function that maps that value to another value. The function simply applies the provided callback:
function mapNumber<T>(value: number, mapfn: (value: number) => T) {
return mapfn(value);
}
We want to set identity
as the default argument for the callback in case no callback is provided by the user:
function identity<T>(x: T) {
return x;
}
// Error: Type '<T>(x: T) => T' is not assignable to type '(value: number) => T'.
// Type 'number' is not assignable to type 'T'.
// 'T' could be instantiated with an arbitrary type which could be unrelated to 'number'
function mapNumber<T>(value: number, mapfn: (value: number) => T = identity) {
return mapfn(value);
}
What might be causing this problem? In theory, since mapfn
is in a contravariant position, it should accept any callback function that is more general than (value: number) => T
, so identity
should suffice, right?