7

什么是 TypeScript 中的函数重载?

 1 year ago
source link: https://www.fly63.com/article/detial/12438
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

更新日期: 2023-04-17阅读: 195标签: 重载分享

扫一扫分享

你知道为什么下图中定义了这么多ref函数,它们是干什么用的吗?如果你还不是很清楚,看完本文的内容,或许你就会明白了。

643ce776ab1a5.jpg

这是一个简单的logError函数,接受一个字符串类型的参数,用于输出错误信息。

function logError(msg: string) {
console.error(`Error occurred: ${msg}`);
}
logError("Missing required field.");

现在问题来了,如果我们想让logError函数以数组的形式支持多条错误信息怎么办?给你几秒钟的时间思考一下,你想出答案了吗?

解决方案之一是使用联合类型:

function logError(msg: string | string[]) {
if (typeof msg === "string") {
console.error(`Error occurred: ${msg}`);
} else if (Array.isArray(msg)) {
console.error(`Errors occurred: ${msg.join("\n")}`);
}
}
logError("Missing required field.");
logError(["Missing required field.", "The length cannot be less than 6."]);

另一种解决方案是使用函数重载,使用函数重载技术,我们需要定义重载签名和实现签名。

643ce79f9232f.jpg

重载签名定义了函数中每个参数的类型和函数的返回值类型,但不包含函数体。一个函数可以有多个重载签名。

643ce7ae38315.jpg

实现签名的参数类型和返回值类型需要使用更通用的类型,同时也包含实现签名的函数体。一个函数只能有一个实现签名。

643ce7b4ba708.jpg

结合重载签名和实现签名后,我们实现了上述功能:

643ce7c56619d.jpg

请注意,只有重载签名是可调用的。当 TypeScript 编译器处理函数重载时,它会查找重载列表并尝试使用第一个重载定义。如果匹配则立即返回。

643ce7cfd10ca.jpg
643ce7fe51ae1.jpg

当使用与实现签名对应的类型的参数调用实现签名函数时,会发生错误。

643ce855b826f.jpg

除了重载函数,我们还可以重载类中的方法。方法重载是指调用同一个类中同名不同参数(参数类型不同、参数个数不同、参数个数相同时参数顺序不同)的方法,而该方法 匹配它被选中,按照实参的形式进行运算。

让我们看一个方法重载的例子:

class Calculator {
add(a: number, b: number): number;
add(a: string, b: string): string;
add(a: string, b: number): string;
add(a: number, b: string): string;
add(a: string | number, b: string | number) {
if (typeof a === 'string' || typeof b === 'string') {
return a.toString() + b.toString();
}
return a + b;
}
}
const calculator = new Calculator();
const result = calculator.add('Bytefer', ' Kakuqo');

看完这篇文章,你应该知道函数重载技术是在vue3响应式模块中ref函数背后使用的。

英文:https://javascript.plainenglish.io/what-are-function-overloads-in-typescript-abcc06af42cb

链接: https://www.fly63.com/article/detial/12438


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK