简体   繁体   English

如何在箭头函数中使用 Typescript 泛型添加两个参数

[英]How to add two arguments using Typescript Generics in Arrow Function

For example I have this code in .tsx file extension例如,我在.tsx file扩展名中有此代码

const Add = <T,>(arg0: T, arg1: T): T => arg0 + arg1;
const A = Add(1, 2);
const B = Add('1', '2')

My problem is that there's an error saying:我的问题是有一个错误说:

Operator '+' cannot be applied to types 'T' and 'T'.ts(2365)

Is there a workaround on how to use it in Arrow function with Generics ?是否有关于如何在带有泛型的Arrow 函数中使用它的解决方法?

Well, first you want to constrain your generics to things you actually intend to use with the + operator;好吧,首先你想把你的泛型限制在你真正打算用+操作符使用的东西上; presumably string or number .大概是stringnumber Then, this will still fail, because the compiler will balk at adding string | number然后,这仍然会失败,因为编译器会拒绝添加string | number string | number . string | number Worse, constraining a generic parameter to extend string | number更糟糕的是,限制泛型参数以扩展string | number string | number will cause the compiler to interpret the input as a either a string literal or a numeric literal type, and you do not want the return type of Add(1, 2) to be 1 | 2 string | number将导致编译器将输入解释为字符串文字数字文字类型,并且您不希望Add(1, 2)的返回类型为1 | 2 1 | 2 . 1 | 2 .

The easiest workaround is to use a type assertion and a conditional type for the return, which widens the result to either string , number , or string | number最简单的解决方法是对返回值使用类型断言条件类型,这会将结果扩展为stringnumberstring | number string | number : string | number :

const Add = <T extends string | number>(
    arg0: T, arg1: T
): T extends string ? string : number => arg0 as any + arg1;

const A = Add(1, 2); // number
const B = Add('1', '2') // string
Add(1, "2"); // compile error
Add("1", 2); // compile error
const C = Add(Math.random() < 0.5 ? 1 : "1", Math.random() < 0.5 ? 2 : "2"); // string | number

Okay, hope that helps;好的,希望有帮助; good luck!祝你好运!

Playground link to code Playground 链接到代码

interface IAdd {
  (a: number, b: number): number
  (a: string, b: string): string
}
const Add: IAdd = (a: any, b: any) => a + b;
Add(1, 1);
Add("1", "2");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM