有没有办法用TypeScript实现以下功能?
function add(x, y) {
return x + y;
}
Run Code Online (Sandbox Code Playgroud)
我想要以下编译:
add(1, 2);
add("hello ", "world");
Run Code Online (Sandbox Code Playgroud)
但我不希望以下编译:
add(4, "world");
add("hello ", 4);
Run Code Online (Sandbox Code Playgroud)
另请注意,我希望它仅针对字符串和数字进行编译.
您可以使用泛型类型执行此操作:
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'
Run Code Online (Sandbox Code Playgroud)
请注意,在调用函数时,您并不总是需要提供泛型类型,只要它满足约束条件:
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'.
Run Code Online (Sandbox Code Playgroud)
如你所见,这是说:
x
并且y
必须是同一类型string
或a number
(或任何一个的扩展)TypeScript编译器非常聪明,可以在不指定调用中的泛型的情况下计算出类型(但必须将它们放在定义中).
正如您所注意到的,这是TypeScript编译器的一个问题.我已经在TypeScript Github repo 上记录了它.
现在,你可以这样做:
function add<T extends string | number>(x: T, y: T): T {
return <any>x + <any>y;
}
Run Code Online (Sandbox Code Playgroud)
x
并且y
仍然是类型T
(由编译器确保)但我们欺骗它让我们+
对它们做.
归档时间: |
|
查看次数: |
190 次 |
最近记录: |