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) { // ... }
void (returns nothing), this should be specified: () => void.this, and overloads also need to be considered when typing.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.
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.