Callbacks and higher-order functions

In TypeScript, functions can be passed as arguments to another function. Functions can also be returned by another function. A function passed to another as an argument is known as a callback. Functions that accept functions as parameters (callbacks) or return functions are known as higher-order functions.

Callbacks are usually anonymous functions. They can be declared before they are passed to the higher-order function, as demonstrated by the following example:

var foo = function() { // callback 
  console.log("foo"); 
} 
 
function bar(cb: () => void) { // higher order function 
  console.log("bar"); 
  cb(); 
} 
 
bar(foo); // prints "bar" then prints "foo" 

However, callbacks are declared inline, at the same point ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.