


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!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools
