同学你好 你这个问题其实很有难度 当然假如没有ts 的话,js 的实现其实就是 a + b,但是由于是联合类型,不能随便使用+,最简单的是用类型断言
const add = (a: string | number, b: string | number) => {
return a as string + b
}
// 当然这个解法在最后返回的类型上是有问题的 add(1,2) 的时候返回的类型是 string,这是有问题的的。
下面的方法你应该还看不懂,不过你可以在学完了以后在回顾一下,这种使用了泛型,并且使用了 extends 进行判定
function add<T extends string | number>(a: T, b: T): T extends string ? string : number
{
return <any>a + <any>b; // Cast to any as unions cannot be added, still have proper typings applied
}
const res1 = add(5, 6) // number
const res2 = add('a', 'b') // string
const res3 = add(5, 'b') // Argument of type '"b"' is not assignable to parameter of type '5'.
第二种使用 function overloading
function add(a: string, b: string): string
function add(a: number, b: number): number
function add(a: any, b: any): string | number
{
return a + b;
}
const res1 = add(1, 2); // Number
const res2 = add('a', 'b'); // String
const res3 = add(1, 'b'); // Overload 1 of 2, '(a: string, b: string): string', gave the following error.