Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
Let JSDoc infer return type of generic high-order function depending on optional parameter

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:

JSDoc hints

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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:

JSDoc hints (as expected)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!