TypeScript,将多个参数绑定到相同类型

时间:2016-11-21 15:29:11

标签: typescript

有没有办法用TypeScript实现以下功能?

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

我想要编译以下内容:

add(1, 2);
add("hello ", "world");

但我不希望编译以下内容:

add(4, "world");
add("hello ", 4);

另请注意,我希望它仅针对字符串和数字进行编译。

2 个答案:

答案 0 :(得分:7)

您可以使用泛型类型执行此操作:

function add<T extends string | number>(x: T, y: T): T {
  return x + y;
}

add<string>("a", "b"); // OK
add<number>(5, 3); // OK
add<boolean>(true, false); // Type 'boolean' does not satisfy constraint 'string | number'

请注意,在调用函数时,并不总是需要给出泛型类型,只要它满足约束条件:

add("a", "b"); // OK
add(5, 3); // OK
add(5, "b"); // Type argument candidate 'number' is not a valid type argument because it is not a supertype of candidate 'string'.
add(true, "c"); // Type argument candidate 'boolean' is not a valid type argument because it is not a supertype of candidate 'string'.

如你所见,这就是说:

  • xy必须是同一类型
  • 该类型必须是stringnumber(或其中任何一个的扩展名)

TypeScript编译器非常聪明,可以在不指定调用中的泛型的情况下计算出类型(但必须将它们放在定义中)。

正如您所注意到的,这是TypeScript编译器的一个问题。我logged it on the TypeScript Github回购。

目前,你可以这样做:

function add<T extends string | number>(x: T, y: T): T {
    return <any>x + <any>y;
}

xy仍为T类型(由编译器确保),但我们欺骗它让我们对它们+

答案 1 :(得分:1)

可以这样做:

function add<T extends string | number>(x: T, y: T): T;
function add(x: any, y: any) {
  return x + y;
}

let s = add("a", "b"); // fine
let n = add(1, 2); // fine
let n2 = add(1,"2"); // error

这就是你现在必须要做的事情,虽然我很高兴@JamesMongar打开了GitHub问题。如果T扩展了原语字符串或数字,那么T上的+运算符肯定是合法的。

相关问题