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

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

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 Denunciar

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 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