union type的问题
来源:2-5 any 类型和联合类型

ywang04
2021-01-03
function combine(input1: number | string , input2: number | string) {
return input1 + input2;
}
const combinedAges = combine(30, 26);
console.log(combinedAges);
老师 我想使用union type 但是如下图所示 input1 + input2 提示有错误。请问如何修改比较好? 谢谢
写回答
1回答
-
同学你好 你这个问题其实很有难度 当然假如没有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.
我不建议你现在去看这些解法 可以先看下去 以后再来看它们的解法
00
相似问题