For example, if there is a method that adds two arguments, a and b, where they must be of the same type, and this type must be a string or a number.
Attempt 1:
function add(a: string | number, b: string | number) { return a + b; }
This will not work because types a and b may not match; therefore, the resulting error makes sense: error TS2365: Operator '+' cannot be applied to types 'string | number' and 'string | number'. error TS2365: Operator '+' cannot be applied to types 'string | number' and 'string | number'.
Attempt 2:
function add<T extends string | number>(a: T, b: T) { return a + b; }
This returns the same error code: error TS2365: Operator '+' cannot be applied to types 'T' and 'T'.
Attempt 3:
function add(a: string, b: string): string; function add(a: number, b: number): number; function add(a: any, b: any) { return a + b; }
This function (function overload) works correctly, but seems redundant. Is there a more elegant way to express it?
generics templates typescript
bjnsn
source share