ProgrammingFullstack Developer / Frontend Developer

How does callback function typing work in TypeScript and what should be considered when typing parameters and return values of callbacks?

Pass interviews with Hintsage AI assistant

Answer

In TypeScript, it is recommended to clearly describe types for callback functions. Defining the types of parameters and the return value helps to prevent errors:

type Callback = (event: string, id: number) => boolean; function useCallback(cb: Callback) { // ... }
  • All parameters and return values should be explicitly typed.
  • If a function can return void (returns nothing), this should be specified: () => void.
  • Closures, this, and overloads also need to be considered when typing.
  • If the callback function is involved in external interactions (for example, React/Node.js), the types must match third-party declarations.

Trick Question

Is it mandatory to specify the types of parameters and return values in the definition of a callback function if TypeScript can infer them automatically?

Answer: Not necessarily, TypeScript can infer the types of callback arguments; however, for public APIs and complex composable functions, it is highly desirable to specify all types explicitly. This facilitates maintenance and prevents unwanted errors when changing function contracts.

Examples of Real Errors Due to Lack of Knowledge on the Topic


Story

In a project, they used a callback without explicit typing of the return value, and one of the developers started returning a string instead of the expected boolean. This did not trigger an error at the compile stage due to the default any, but the logic of the function broke, causing a bug in production.


Story

In a large React project, they forgot to explicitly type the event callback parameters. When upgrading to a new version of React, the event types changed, and the code started compiling with errors. They had to urgently fix the callback function on all pages.


Story

In a Node.js application, the callback for working with an asynchronous function was not typed: the returned value was mistakenly interpreted as a string, while it was an error object. The type mismatch led to an inability to correctly handle errors.