Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!