有没有办法用TypeScript实现以下内容?TypeScript,绑定多个参数到相同的类型
function add(x, y) {
return x + y;
}
我想下面的编译:
add(1, 2);
add("hello ", "world");
但我不希望下面的编译:
add(4, "world");
add("hello ", 4);
还请注意,我希望它编译字符串和数字只要。
有没有办法用TypeScript实现以下内容?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
必须SA我型string
或number
(或其中的扩展)打字稿编译器足够聪明摸出类型没有在调用指定泛型(但是你必须把它们放在定义中)。
正如您所注意到的,这是TypeScript编译器的问题。我有logged it on the TypeScript Github回购。
现在,你可以这样做:
function add<T extends string | number>(x: T, y: T): T {
return <any>x + <any>y;
}
x
和y
仍然T
型(由编译器保证),但我们诱骗到让我们对他们做+
。
可悲的是,它确实没有编译... '运算符'+'不能应用于类型'T'和'T'' – Balzard
您正在使用哪种版本的TypeScript?这可能是编译器的问题。 –
@JamesMonger Nope,即使在打字稿2.2(@next)中也不起作用。 –
这是可以做到这样的:
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上的+运算符肯定是合法的。
很好的解决方案@Erigotto –
也许是一个重复:http://stackoverflow.com/questions/32357839/typescript-how-to-express-a-generic-function-where-the-type-is-restricted-to-on – Paleo