Assuming the following function:
/**
* @template T
* @template U
* @param { T } item
* @param { function(T): U } [mapper = t => t]
* @returns { U }
*/
function map(item, mapper = t => t) {
return mapper(item);
}
I would expect JSDoc to be able to infer the type of each of one and two in this snippet:
const one = map('123', parseInt); // should be `number`
const two = map('123'); // should be `string`
Unfortunately, it appears that, when the optional mapper function isn't provided, the resulting type isn't inferred and two is just assumed to be any, as illustrated below:
I was hoping that documenting the mapper parameter of my map function as to be optional and having a default value (as documented here would be enough.
What am I missing? Surely it must be possible!
The proper implementation of the JSDoc type-inference for the map function is...
/**
* @template T
* @template [U = T]
* @param { T } item
* @param { function(T): U } [mapper = t => t]
* @returns { U }
*/
function map(item, mapper = t => t) {
return mapper(item);
}
The sole difference is in the declaration of the return-type template U:
/** @template U */
... needs to become:
/** @template [U = T] */
This lets your type-inference system understand that the generic type U, when unable to be inferred, should default to being equivalent to T!
This seems to only be documented in the TypeScript JSDoc reference. It does appear to function, as illustrated below: