← Back to course: TypeScript from scratch

Callbacks, this and functions review

Video coming soon

In JavaScript we pass functions as arguments all the time: in map, filter, addEventListener, setTimeout or in promises. Those functions are called callbacks. Typing them well is what makes autocompletion and errors work inside the callback. The good news is that you almost never have to annotate the parameters of a callback you write inline, because TypeScript infers them from the function receiving it. What you do need to know is how to declare a parameter that accepts a callback yourself.

Typed callbacks

The parameter type describes the shape of the expected function: which arguments it receives and what it returns. When the callback returns nothing you care about, the return is void. A useful nuance: a function with a void return accepts callbacks that return something else, because the value is simply ignored. That is why you can pass arr.push to a forEach without errors.

typescript
function repeatAction(times: number, action: (index: number) => void): void {
  for (let i = 0; i < times; i++) {
    action(i);
  }
}

repeatAction(3, (i) => console.log('Run ' + i)); // i inferred as number

function transformAll(items: string[], transform: (item: string) => string): string[] {
  const result: string[] = [];
  for (const item of items) {
    result.push(transform(item));
  }
  return result;
}

console.log(transformAll(['a', 'b'], (s) => s.toUpperCase())); // ['A', 'B']

const lengths = ['one', 'three'].map((word) => word.length); // number[]
console.log(lengths);

Functions that return functions

A function can return another function, and the return type is simply a function type. It is a common pattern for creating configurable functions, such as a multiplier or a validator. The compiler remembers the type of captured variables, so the closure ends up fully typed with no extra effort.

typescript
function makeMultiplier(factor: number): (value: number) => number {
  return (value) => value * factor;
}

const triple = makeMultiplier(3);
console.log(triple(7)); // 21

type Predicate<T> = (item: T) => boolean;

function countMatches(items: number[], test: Predicate<number>): number {
  return items.filter(test).length;
}

console.log(countMatches([1, 2, 3, 4, 5, 6], (n) => n % 2 === 0)); // 3

A quick look at this

In JavaScript, the value of this depends on how the function is called, and that causes many bugs. TypeScript lets you declare the type of this as a fake first parameter, which disappears when compiling. With strict on (the noImplicitThis option), using this in a loose function without declaring it is an error. In modern practice the problem is avoided by using arrow functions, which capture the this of the context where they are written, or classes, which we will see in week 6.

A note on promises, because asynchronous callbacks are very common. An async function always returns a promise, so its return type is written Promise<T>: async function load(): Promise<string>. If you forget the await when using the result, TypeScript will warn you that you are treating a promise as if it were the value, one of the most frequent mistakes for beginners. Also keep in mind that an async callback passed where a void callback is expected is awaited by nobody, and its errors can be lost without warning.

Test what you learned

Question 1 of 6

How do you mark a parameter as optional?

✎ My notes

Saved only in this browser. Sign in to keep it in your account.0/5000 characters

← PreviousNext →