


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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

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.


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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools
