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

205
Visualizações
callback function returning value passes type check as void function in TypeScript

I am currently learning TypeScript, and my understanding is that specifying a type for any variable/function should prompt TypeScript to enforce a type-check on its computed value, with the exception of type any.

However, I was surprised today to find that when I created a function with a parameter of type () => void, and the function passed into that function does return something, there was no error from TypeScript. Why is this?

function doSomething(callback: () => void) : void {
  callback();
  // callback is of type `void`, so shouldn't this cause an error?
}
 
doSomething(() => 1); // will return 1 when invoked

Interestingly, when I try to store and use the returned value, I do get an error from TypeScript:

function doSomething(callback: () => void) : void {
  let a = callback();
  console.log(a + 1); // 🚫 Operator '+' cannot be applied to types 'void' and 'number'.
}
 
doSomething(() => 1);

From this example, it appears a is still stored as type void even though the callback function should be returning 1. What's happening under the hood here?

about 4 years ago · Juan Pablo Isaza
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