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

215
Visualizações
Define a function that returns a function that returns void

I don't understand why this gives an error

function foo(): () => string {
  return () => 123;
}

But this does not

function foo(): () => void {
  return () => 123;
}

And also this will not give an error as well

function foo(): (a: number) => string {
  return () => '123';
}

I explicitly type that returned function should accept one argument, then return a function that does not accept any, but TS does not give me any error.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Assigning a function of type () => number to something of type () => string clearly is a type error. However, for void as a return type, TypeScript is more lenient. From the handbook on the Assignability of Functions:

The void return type for functions can produce some unusual, but expected behavior.

Contextual typing with a return type of void does not force functions to not return something. Another way to say this is a contextual function type with a void return type (type vf = () => void), when implemented, can return any other value, but it will be ignored.

[…]

There is one other special case to be aware of, when a literal function definition has a void return type, that function must not return anything.

There's also an FAQ entry about it.

about 4 years ago · Juan Pablo Isaza Relatório

0

My investigations ended up with a fact that it is impossible to do this with TypesScript, unfortunately. Here are the links that explain why this unintuitive decision was made

  1. Void type
  2. Assignability of functions
  3. FAQ

The solution that is closest to the desired functionality is to

  1. Type returned function to return undefined
function foo(): () => undefined { ... }
  1. Set on option in tsconfig.json
"compilerOptions": {"noImplicitReturns": false}
  1. Explicitly return from the returned function
function foo(): () => undefined { 
    return () => { return; }
}

Looks a bit ugly but now we can define a function that for sure will return nothing.

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