function f<T, U>(foo: T, bar: U) {
}
f(1, "x"); // OK, inferes <number, string>
f<number>(1, "x"); // ERROR: Expected 2 type arguments, but got 1.
How can I pass only the first type argument and let TypeScript infer the other?
As @Joe-Clay says, you can set default parameters to make generics optional, but the compiler will not infer them the way you want.
A workaround I've used is to split functions up into multiple ones (via currying), each with one generic parameter. For example:
function f<T,U>(foo:T, bar: U): [T, U] {
return [foo, bar];
}
becomes
function curriedF<T>(foo: T) {
return function <U>(bar: U): [T, U] {
return [foo, bar]
}
}
Which allows this:
var z = curriedF(1)("x"); // [number, string]
var z = curriedF<number>(1)("x"); // also [number, string]
Hope that helps; good luck.
There is some progress on partial inference (using the *
sigil to mark "please infer this for me") and it might be present in TypeScript 3.2 or thereabouts. See this pull request for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With