1

For example I have this code in .tsx file extension

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?

0

2 Answers 2

2

Well, first you want to constrain your generics to things you actually intend to use with the + operator; presumably string or number. Then, this will still fail, because the compiler will balk at adding string | number. Worse, constraining a generic parameter to extend 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.

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:

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

Sign up to request clarification or add additional context in comments.

Comments

1
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");

2 Comments

But not in arrow function
Code-only answers are considered low quality: make sure to provide an explanation what your code does and how it solves the problem. It will help the asker and future readers both if you can add more information in your post. See also Explaining entirely code-based answers: meta.stackexchange.com/questions/114762/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.