


How to write function overloading in TypeScript? Introduction to writing
How to write function overloading in TypeScript? The following article will introduce to you how to write function overloading in TypeScript. I hope it will be helpful to you!
Most functions accept a fixed set of parameters.
But some functions can accept a variable number of parameters, different types of parameters, and even return different types depending on how you call the function. To annotate such functions, TypeScript provides function overloading.
1. Function signature
Let’s first consider a function that returns a greeting message to a specific person.
function greet(person: string): string { return `Hello, ${person}!`; }
The above function accepts 1 character type parameter: the person’s name. Calling this function is very simple:
greet('World'); // 'Hello, World!'
What if you want to make the greet()
function more flexible? For example, let it additionally accept a list of people to greet.
Such a function will accept a string or string array as a parameter and return a string or string array.
How to annotate such a function? There are 2 ways.
The first method is very simple, which is to directly modify the function signature by updating the parameters and return type. The following refactoring greet()
looks like:
function greet(person: string | string[]): string | string[] { if (typeof person === 'string') { return `Hello, ${person}!`; } else if (Array.isArray(person)) { return person.map(name => `Hello, ${name}!`); } throw new Error('Unable to greet'); }
Now we can call greet()
in two ways:
greet('World'); // 'Hello, World!' greet(['小智', '大冶']); // ['Hello, 小智!', 'Hello, 大冶!']
Directly updating function signatures to support multiple calling methods is a common and good approach.
However, in some cases, we may need to take another approach and separately define all the ways in which your function can be called. This method is called function overloading.
2. Function overloading
The second method is to use the function overloading function. I recommend this approach when the function signature is relatively complex and involves multiple types.
Defining function overloading requires defining an overload signature and an implementation signature.
The overload signature defines the formal parameters and return type of the function, without a function body. A function can have multiple overload signatures: corresponding to different ways of calling the function.
On the other hand, the implementation signature also has parameter types and return types, and also has the body of the implementation function, and there can only be one implementation signature.
// 重载签名 function greet(person: string): string; function greet(persons: string[]): string[]; // 实现签名 function greet(person: unknown): unknown { if (typeof person === 'string') { return `Hello, ${person}!`; } else if (Array.isArray(person)) { return person.map(name => `Hello, ${name}!`); } throw new Error('Unable to greet'); }
greet()
The function has two overload signatures and an implementation signature.
Each overload signature describes a way in which the function can be called. As far as the greet()
function is concerned, we can call it in two ways: with a string parameter, or with a string array parameter.
Implementation signature function greet(person: unknown): unknown { ... }
Contains the appropriate logic for how the function works.
Now, as above, greet()
can be called with arguments of type string or array of strings.
greet('World'); // 'Hello, World!' greet(['小智', '大冶']); // ['Hello, 小智!', 'Hello, 大冶!']
2.1 The overloaded signature is callable
Although the implementation signature implements the function behavior, it cannot be called directly. Only overloaded signatures are callable.
greet('World'); // 重载签名可调用 greet(['小智', '大冶']); // 重载签名可调用 const someValue: unknown = 'Unknown'; greet(someValue); // Implementation signature NOT callable // 报错 No overload matches this call. Overload 1 of 2, '(person: string): string', gave the following error. Argument of type 'unknown' is not assignable to parameter of type 'string'. Overload 2 of 2, '(persons: string[]): string[]', gave the following error. Argument of type 'unknown' is not assignable to parameter of type 'string[]'.
In the above example, even though the implementation signature accepts unknown
parameters, it cannot be called with a parameter of type
unknown (greet(someValue)) greet()
function.
2.2 The implementation signature must be universal
// 重载签名 function greet(person: string): string; function greet(persons: string[]): string[]; // 此重载签名与其实现签名不兼容。 // 实现签名 function greet(person: unknown): string { // ... throw new Error('Unable to greet'); }
Overloaded signature functiongreet(person: string[]): string[ ]
is marked as incompatible with greet(person: unknown): string
.
The return type of the string
implementation of the signature is not general enough and is not compatible with the overloaded signature's string[]
return type.
3. Method overloading
Although in the previous example, function overloading is applied to an ordinary function. But we can also overload a method
In the method overloading interval, the overloading signature and implementation signature are part of the class.
For example, we implement a Greeter
class with an overloaded method greet()
.
class Greeter { message: string; constructor(message: string) { this.message = message; } // 重载签名 greet(person: string): string; greet(persons: string[]): string[]; // 实现签名 greet(person: unknown): unknown { if (typeof person === 'string') { return `${this.message}, ${person}!`; } else if (Array.isArray(person)) { return person.map(name => `${this.message}, ${name}!`); } throw new Error('Unable to greet'); }
Greeter Class contains greet()
Overloaded methods: 2 overload signatures describing how to call the method, and an implementation signature containing the correct implementation
Due to method overloading, we can call hi.greet()
in two ways: using a string or using an array of strings as a parameter.
const hi = new Greeter('Hi'); hi.greet('小智'); // 'Hi, 小智!' hi.greet(['王大冶', '大冶']); // ['Hi, 王大冶!', 'Hi, 大冶!']
4. When to use function overloading
Function overloading, if used properly, can greatly increase the usability of a function that may be called in multiple ways. This is particularly useful during autocompletion: we list all possible overloads in autocompletion.
However, in some cases it is recommended not to use function overloading and instead use function signatures.
For example, do not use function overloading for optional parameters:
// 不推荐做法 function myFunc(): string; function myFunc(param1: string): string; function myFunc(param1: string, param2: string): string; function myFunc(...args: string[]): string { // implementation... }
It is sufficient to use optional parameters in the function signature:
// 推荐做法 function myFunc(param1?: string, param2: string): string { // implementation... }
5. Summary
Function overloading in TypeScript lets us define functions that are called in multiple ways.
Using function overloading requires defining an overload signature: a set of functions with parameters and return types, but no body. These signatures indicate how the function should be called.
Additionally, you must write the correct implementation (implementation signature) of the function: parameters and return types, as well as the function body . Note that implementation signatures are not callable.
In addition to regular functions, methods in classes can also be overloaded.
English original address: https://dmitripavltin.com/typeript-function-overloading/
Author: dmitripavlutin
Translator: Front-end Xiaozhi
For more programming-related knowledge, please visit: Introduction to Programming! !
The above is the detailed content of How to write function overloading in TypeScript? Introduction to writing. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Function overloading allows functions with the same name but different signatures in a class, while function overriding occurs in a derived class when it overrides a function with the same signature in the base class, providing different behavior.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Function overloading and rewriting are supported in PHP to create flexible and reusable code. Function overloading: allows the creation of functions with the same name but different parameters, and calls the most appropriate function based on parameter matching. Function rewriting: Allow subclasses to define functions with the same name and override parent class methods. When subclass methods are called, they will override parent class methods.

Ambiguous calls occur when the compiler cannot determine which overloaded function to call. Solutions include providing a unique function signature (parameter type and number) for each overloaded function. Use explicit type conversion to force the correct function to be called if an overloaded function's parameter types are more suitable for the parameters of a given call. If the compiler cannot resolve an ambiguous call, an error message will be generated and the function overloading will need to be rechecked and modified.

The Go language does not support traditional function overloading, but similar effects can be achieved through the following methods: using named functions: creating unique names for functions with different parameters or return types; using generics (Go1.18 and above): creating unique names for different types of parameters A single version of the function.

Best practices for C++ function overloading: 1. Use clear and meaningful names; 2. Avoid too many overloads; 3. Consider default parameters; 4. Keep the parameter order consistent; 5. Use SFINAE.

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

The C++ function overload matching rules are as follows: match the number and type of parameters in the call. The order of parameters must be consistent. The constness and reference modifiers must match. Default parameters can be used.
