Home > Web Front-end > JS Tutorial > body text

How to write function overloading in TypeScript? Introduction to writing

青灯夜游
Release: 2021-12-14 10:37:01
forward
2012 people have browsed it

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}!`;
}
Copy after login

The above function accepts 1 character type parameter: the person’s name. Calling this function is very simple:

greet('World'); // 'Hello, World!'
Copy after login

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');
}
Copy after login

Now we can call greet() in two ways:

greet('World');          // 'Hello, World!'
greet(['小智', '大冶']); // ['Hello, 小智!', 'Hello, 大冶!']
Copy after login
Copy after login

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');
}
Copy after login

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, 大冶!']
Copy after login
Copy after login

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[]'.
Copy after login

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');
}
Copy after login

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');
  }
Copy after login

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, 大冶!']
Copy after login

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...
}
Copy after login

It is sufficient to use optional parameters in the function signature:

// 推荐做法
function myFunc(param1?: string, param2: string): string {
  // implementation...
}
Copy after login

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!

source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template