小编Jus*_*yer的帖子

如何在 TypeScript 中创建一个适用于数字和字符串的通用加法运算符

在学习 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

4
推荐指数
1
解决办法
931
查看次数