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

Jus*_*yer 4 generics type-inference operators type-constraints 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 就会知道它是添加两个字符串两个数字。

Spe*_*ark 6

也可能发生的一种情况MyTypestring | numberwhich extends StringOrNumber。例如add<string | number>('', 1);,使用您定义的签名对函数进行完全有效的调用。扩展联合类型的类型并不意味着“选择一个”。

由于您的签名有意义并且您正在学习泛型,因此我们想坚持使用它,我们也可以在此时关闭类型检查。有时打字稿真的无法弄清楚您的复杂场景,此时您别无选择,return (x as any) + y只能放弃类型检查。

处理这种情况的另一种方法是使用像下面这样的重载签名

function add(x: string, y: string): string;
function add(x: number, y: number): number;
function add(x: any, y: any): any {
    return x + y;
}

const t1: string = add(10, 1); // Type 'number' is not assignable to type 'string'.
const t2: number = add(10, 1); // OK
const t3: string = add('10', '1'); // OK
const t4: number = add('10', 1); // Argument of type '"10"' is not assignable to parameter of type 'number'.
Run Code Online (Sandbox Code Playgroud)