likes
comments
collection
share

Vue3源码中的TypeScript重载函数的作用

作者站长头像
站长
· 阅读数 16

TypeScript重载函数的作用案例

C++中的一个概念(百度百科):

函数重载一般指重载函数。 重载函数是函数的一种特殊情况,为方便使用,C++允许在同一范围中声明几个功能类似的同名函数,但是这些同名函数的形式参数(指参数的个数、类型或者顺序)必须不同,也就是说用同一个函数完成不同的功能。这就是重载函数。

简要总结就是

函数的名称相同, 但是参数不同的几个函数, 就是函数的重载。

1.Vue3 ref声明方法的源码中重载函数案例

Vue3源码中的TypeScript重载函数的作用

2.举一个应用场景中的案例缺点

function ToAdd (a: string | number, b: string | number): string | number | undefined {
// 只需要字符串合并
if (typeof a === 'string' && typeof b === 'string') {
return `${a + b}`;
};
// 只需要数字想加
if (typeof a === 'number' && typeof b === 'number') {
return a + b;
};
} 

大量联合类型有两个缺点:

如果业务中有类似的需求,添加大量联合类型声明 需要专门的逻辑进行判断,而且最终返回值是 string 还是 number 也不能确定。

编辑器提示无法确定是 string 还是 number。Vue3源码中的TypeScript重载函数的作用

3.使用重载函数解决问题

//  重载声明2次 不需要加函数体
function ToAdd(a: number, b: number): number;
function ToAdd(a: string, b: string): string;
function ToAdd(a: any, b: any): any {
if (typeof a === 'string' && typeof b === 'string') {
return `${a + b}`;
}
return a + b;
}

const test = ToAdd(1, '233'); // 异常提示

异常提示Vue3源码中的TypeScript重载函数的作用

// 编辑器也能识别出对应类型
const addString = ToAdd('233', '233'); // 正确 编辑器识别出 const addString: string
const addNum = ToAdd(1, 1); // 正确 编辑器识别出 const addNum: number

Vue3源码中的TypeScript重载函数的作用