Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze the method of function overloading in TypeScript

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about how to analyze the overloading of functions in TypeScript. Many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.

Foreword:

Most functions accept a fixed set of parameters. However, some functions can accept a variable number of parameters, different types of parameters, and even return different types depending on the way 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 for a particular person.

Function greet (person: string): string {return `Hello, ${person}! `;}

The above function accepts an argument of 1 character type: the person's name. Calling this function is very simple:

Greet ('World'); / /' Hello, Worldwide'

What if you want to make the greet () function more flexible? For example, ask it to accept another list of people to greet.

Such a function takes a string or an array of strings as an argument and returns a string or an array of strings.

How to annotate such a function? There are two ways.

The first method is simple, which is to modify the function signature directly by updating the parameters and the return type.

The following reconstructed 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, Worldwide wisdom greet (['Hello', 'Daye']); / / ['Hello, Hsiao Zhi!', 'Hello, Daye!']

It is a common and good method to update the function signature directly to support multiple calls.

In some cases, however, we may need to take a different approach, defining all the ways in which your function can be called. This method is called function overloading.

two。 Function overload

The second method is to use the function overloading function. I recommend this method when function signatures are relatively complex and involve multiple types.

Defining a function overload requires defining an overload signature and an implementation signature.

The overloaded signature defines the formal parameters and return types of the function, without the function body. A function can have multiple overloaded signatures: corresponding to different ways in which the function is called.

On the other hand, the implementation signature also has a parameter type and a return type, and there is a body that implements the function, and there can only be one implementation signature.

/ / overload signature function greet (person: string): string;function greet (persons: string []): string []; / / implement signature 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');}

The greet () function has two overloaded signatures and an implementation signature.

Each overloaded 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 argument, or with a string array argument.

Implement the signature function greet (person: unknown): unknown {...} contains the appropriate logic for how the function works.

Now, as above, you can call greet () with parameters of a string or string array type.

Greet ('World'); / /' Hello, Worldwide overloaded greet (['Hsiao Zhi', 'Daye']); / / ['Hello, Hsiao Zhi!', 'Hello, Daye!'] 2.1 overloaded signature is callable

Although the implementation signature implements the function behavior, it cannot be called directly. Only the overloaded signature is callable.

Greet ('World'); / / overloaded signature can call greet ([' Xiaozhi', 'Daye']); / / overloaded signature can call const someValue: unknown = 'Unknown';greet (someValue); / / Implementation signature NOT callable// error 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 if the implementation signature accepts the unknown parameter, the greet () function cannot be called with a parameter of type unknown (greet (someValue)).

2.1 the implementation signature must be universal

/ / overloaded signature function greet (person: string): string;function greet (persons: string []): string []; / / this overloaded signature is not compatible with its implementation signature. / / implement signature function greet (person: unknown): string {/ /... Throw new Error ('Unable to greet');}

The overloaded signature function greet (person: string []): string [] is marked as incompatible with greet (person: unknown): string.

The string return type that implements the signature is not generic enough to be compatible with the string [] return type of the overloaded signature.

3. Method overload

Although in the previous example, function overloading is applied to a normal function. But we can also overload a method

In the method overloading interval, both the overloaded signature and the 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;} / / overload signature greet (person: string): string; greet (persons: string []): string []; / / implement signature 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');}

The Greeter class contains the greet () overloaded method: two overloaded signatures describe how to call the method and the implementation signature that contains the correct implementation

Because of method overloading, we can call hi.greet () in two ways: using a string or using an array of strings as an argument.

Const hi = new Greeter ('Hi'); hi.greet (' Xiaozhi'); / /'Hi, Xiaozhi! 'hi.greet ([' Wang Daye', 'Daye']); / / ['Hi, Wang Daye!','Hi, Daye!'] 4. When to use function overloading

Function overloading, if used properly, can greatly increase the availability of functions that may be called in many ways. This is especially useful in automatic completion: we list all possible overloaded records in automatic completion.

In some cases, however, it is recommended that you do not use function overloading, but rather use function signatures.

For example, do not use function overloading for optional parameters:

/ / deprecated practice 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 a function signature:

/ / recommended practice function myFunc (param1?: string, param2: string): string {/ / implementation...} 5. Summary

Function overloading in TypeScript allows us to define functions that are called in a variety of ways.

Using function overloading requires defining overloaded signatures: a set of functions with arguments and return types, but no body. These signatures indicate how the function should be called.

After reading the above, do you have any further understanding of how to parse function overloading in TypeScript? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report