问题
Why does the typescript compiler throw the following error:
Operator '+' cannot be applied to types 'T' and 'T'.
,
when compiling:
export const addNumbersOrCombineStrings = <T extends string | number>(
param1: T,
param2: T
): T => param1 + param2
?
回答1:
The relevant issue in GitHub is Microsoft/TypeScript#12410. Your particular question is addressed in a comment by Ryan Cavanaugh:
T + T
whereT
extendsstring | number
is still disallowed -- we don't feel this is a good use case because whether you get concatenation or addition is not predictable, thus something that people shouldn't be doing.
The same thing happens to you if you just try to add two string | number
types together:
declare const x: string | number;
x + x; // error!
// Operator '+' cannot be applied to types 'string | number' and 'string | number'.
So I guess they are serious that they don't want you doing that. You can always bend the compiler to your will and disable the type check with a type assertion;
export const addNumbersOrCombineStrings = <T extends string | number>(
param1: T,
param2: T
): T => (param1 as any) + param2;
But you don't want to do this, especially since T extends string | number
will infer a string or number literal, which does not give you the behavior you expect:
const notThree = addNumbersOrCombineStrings(1, 2);
// const notThree: 1 | 2
const notHi = addNumbersOrCombineStrings("h", "i");
// const notHi: "h" | "i"
Oops, those results are unions of literals. And to fix that with generics you'd probably want to start using fancy conditional types to widen the literals:
type SN<T extends string | number> = (T extends string ? string : never) |
(T extends number ? number : never);
export const addNumbersOrCombineStrings = <T extends string | number>(
param1: T,
param2: SN<T>
): SN<T> =>
(param1 as any) + param2;
const n = addNumbersOrCombineStrings(1, 2); // const n : number;
const s = addNumbersOrCombineStrings("h","i"); // const s: string;
// and do you even want to support this:
const sn = addNumbersOrCombineStrings(
Math.random() < 0.5 ? "a" : 1,
Math.random() < 0.5 ? "b" : 2
); // const sn: string | number;
But there are edge cases there too, probably (like when the value passed in is actually string | number
like the sn
case above). I'm starting to see why they don't feel like supporting adding values of type string | number
together. Anyway, hope that helps. Good luck!
来源:https://stackoverflow.com/questions/55987256/typescript-generics-union-constraint