Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda