有没有办法用 TypeScript 实现以下目标?
function add(x, y) {
return x + y;
}
我要编译以下内容:
add(1, 2);
add("hello ", "world");
但我不想编译以下内容:
add(4, "world");
add("hello ", 4);
另请注意,我希望它仅针对字符串和数字进行编译。
最佳答案
您可以使用泛型来做到这一点:
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
类型(由编译器确保)但是我们欺骗它让我们做 +
在他们身上。
关于TypeScript,将多个参数绑定(bind)到同一类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40723718/