Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

176
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda