search
HomeWeb Front-endJS TutorialHow to write function overloading in TypeScript? Introduction to writing

How to write function overloading in TypeScript? Introduction to writing

Dec 14, 2021 am 10:37 AM
javascripttypescriptfunction overloading

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!

How to write function overloading in TypeScript? Introduction to writing

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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools