While learning about generics in TypeScript, I wanted to try to recreate the following JavaScript:
function add(x, y){
return x + y;
}
I tried like:
type StringOrNumber = string | number;
function add<MyType extends StringOrNumber>(x: MyType, y: MyType): MyType {
return x + y;
}
This errors with:
error TS2365: Operator '+' cannot be applied to types 'MyType' and 'MyType'.
Why doesn't this work? I'd assume that MyType
could be either a string or a number, and once "chosen" TypeScript would know it is either adding two strings or two numbers.