callback function returning value passes type check as void function in TypeScript

Viewed 14

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?

0 Answers
Related