Functions and generics

Type callbacks

Describe the parameters and result of a function passed as a value.

In JavaScript, functions are values. You pass them to array methods, event handlers, and utilities all the time. TypeScript needs a way to describe those values, and that is what a function type does.

A function type describes how another function may be called:

function transform(value: string, fn: (value: string) => string) {
  return fn(value)
}

Read (value: string) => string as “a function that takes one string and returns a string”. The arrow separates parameters from the result. Now transform() can only receive callbacks matching that contract — passing (n: number) => n * 2 fails at the call site, not deep inside the body.

Parameter names inside the type are documentation; compatibility depends on their types and positions. (text: string) => string and (value: string) => string are the same type.

Inference inside inline callbacks

Context gives an inline callback its parameter type:

const result = transform('hello', value => value.toUpperCase())

You do not need to annotate value again. TypeScript looks at the type of fn and knows value is a string. This is why callbacks in .map() and .filter() rarely need annotations: the array’s element type flows in.

void callbacks

Use void when the caller ignores the callback result:

function visit(fn: (title: string) => void) {
  fn('TypeScript')
}

A void return type means “whatever this returns, I will not use it”. You can still pass a callback that returns something — visit(title => title.length) is fine — because ignoring a value is always safe. That flexibility is deliberate and makes void the right default for handlers and listeners.

One trap with optional parameters

Be careful with optional callback parameters. Writing (index?: number) => void means your code may call the callback without an index. It does not mean callers can ignore a required argument you always provide. If you always pass the index, declare it required: callers who do not need it can write a callback with fewer parameters, which TypeScript accepts.

Exercise: change transform() so the callback converts a string into a number. Confirm that the function result becomes number.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →