乐闻世界logo
搜索文章和话题

How can you define function overloads in TypeScript?

1个答案

1

In TypeScript, defining function overloading enables you to specify multiple function type signatures for a single function. This approach enhances the flexibility of function calls while maintaining type safety. Below, I'll demonstrate how to define and implement function overloading in TypeScript with an example.

First, declare all overload signatures before the function implementation. Then, implement a function body capable of handling all overload scenarios.

For example, consider a function add that can take two numbers or two strings and return their sum or concatenation. If the inputs are numbers, it returns their sum; if they are strings, it returns their concatenation. Here's how to define this function's overloads:

typescript
// Overload signatures function add(x: number, y: number): number; function add(x: string, y: string): string; // Function implementation function add(x: any, y: any): any { if (typeof x === "number" && typeof y === "number") { return x + y; // Handle number addition } else if (typeof x === "string" && typeof y === "string") { return x + y; // Handle string concatenation } throw new Error('Invalid arguments. Both arguments must be either numbers or strings.'); } // Using the function console.log(add(5, 10)); // Output: 15 console.log(add("Hello, ", "world!")); // Output: "Hello, world!"

In the above code, the add function first defines two overload signatures:

  • One that accepts two number parameters and returns a number.
  • Another that accepts two string parameters and returns a string.

The implementation (function add(x: any, y: any): any) uses type checking to determine which operation to perform. This implementation must handle all declared overload cases. Note that the implementation is not exposed externally; only the overload signatures form the public interface.

Using overloading clearly informs users of the allowed parameter combinations while maintaining implementation flexibility and reusability. This is particularly useful when building large projects, improving code maintainability and readability.

2024年8月2日 13:45 回复

你的答案