首页 > 解决方案 > 如何在 TypeScript 中创建适用于数字和字符串的通用加法运算符

问题描述

在学习 TypeScript 中的泛型时,我想尝试重新创建以下 JavaScript:

function add(x, y){
    return x + y;
}

我试过像:

type StringOrNumber = string | number;

function add<MyType extends StringOrNumber>(x: MyType, y: MyType): MyType {
    return x + y;
}

这与以下错误有关:

error TS2365: Operator '+' cannot be applied to types 'MyType' and 'MyType'.

为什么这不起作用?我假设它MyType可能是一个字符串或一个数字,一旦“选择”TypeScript 就会知道它是添加两个字符串还是两个数字。

标签: typescriptgenericsoperatorstype-inferencetype-constraints

解决方案


也可能发生的情况是 that MyTypecan be string | 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'.

推荐阅读