您可以使用泛型类型来做到这一点:
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'.
如您所见,这是在说:
-
x 和 y 必须是同一类型
- 该类型必须是
string 或 number(或两者的扩展)
TypeScript 编译器足够聪明,无需在调用中指定泛型即可计算出类型(但您必须将它们放在定义中)。
如您所见,这是 TypeScript 编译器的问题。我有logged it on the TypeScript Github repo。
目前,您可以这样做:
function add<T extends string | number>(x: T, y: T): T {
return <any>x + <any>y;
}
x 和 y 仍然是 T 类型(由编译器确保),但我们欺骗它让我们对它们执行 +。