在学习 TypeScript 中的泛型时,我想尝试重新创建以下 JavaScript:
function add(x, y){
return x + y;
}
Run Code Online (Sandbox Code Playgroud)
我试过:
type StringOrNumber = string | number;
function add<MyType extends StringOrNumber>(x: MyType, y: MyType): MyType {
return x + y;
}
Run Code Online (Sandbox Code Playgroud)
此错误与:
error TS2365: Operator '+' cannot be applied to types 'MyType' and 'MyType'.
Run Code Online (Sandbox Code Playgroud)
为什么这不起作用?我假设它MyType
可以是一个字符串或一个数字,一旦“选择”TypeScript 就会知道它是添加两个字符串或两个数字。
generics type-inference operators type-constraints typescript