"No overload matches this call" in TypeScript
October 30, 2023
If you're a TypeScript developer, you've likely encountered the "No overload matches this call" error at some point. This guide aims to shed light on why this error occurs and how to resolve it.
Understanding the Error
The "No overload matches this call" error occurs when you try to call a function (or a method) that has multiple overload signatures, but none of these overloads match the arguments you provided.
The most straightforward cause is passing arguments of the wrong type or the wrong number of arguments.
In the above example, there are two overloads for the
example function. The first expects a
string followed by a
number, and the second expects a
number followed by a
string. Neither of these overloads matches the
(123, 456) call.
Sometimes, the error arises when the function expects its context (
this) to be of a certain type.
Array.prototype.forEach expects a callback of type
(value: T, index: number, array: T) => void. But when
handle is passed to
forEach, TypeScript assumes that
handle can be anything, which could lead to runtime errors.
Correct the Arguments
Ensure the arguments you're passing match one of the function's overload signatures.
Binding the Function Context
If the error is due to a context issue, bind the function to the correct context:
Or use an arrow function to maintain the correct context:
Extend Overload Signatures
If you're in control of the function's declaration, and the missing overload is legitimate, add the required overload:
Utilize Type Assertions
Sometimes, you're sure of the types you're working with, but TypeScript isn't. In such cases, you can use type assertions:
Note: Use type assertions with caution. Bypassing TypeScript's type safety defeats the purpose of using TypeScript in the first place.
Generics can also cause overload issues. Ensure that if the function or method is generic, you're either providing the generic type or allowing TypeScript to correctly infer it.
Tooling and Resources
- TypeScript Playground: Before making changes to your code, you can try to reproduce the issue in the TypeScript Playground. This will help you isolate the problem and test potential solutions.
- TypeScript Docs: The official TypeScript documentation is a valuable resource for understanding function overloads and type checking in depth.
By understanding the underlying causes of the "No overload matches this call" error and leveraging the provided solutions, you can write safer, cleaner TypeScript code.
How to fix the "not all code paths return a value" issue in TypeScript
Working with WebSockets in Node.js using TypeScript
Type Annotations Can Only Be Used in TypeScript Files
Guide to TypeScript Recursive Type
How to Configure Knex.js with TypeScript