Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify only first type argument

Tags:

typescript

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?

like image 339
kraftwer1 Avatar asked Dec 18 '22 05:12

kraftwer1


1 Answers

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.


UPDATE 2018-10-19

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.

like image 193
jcalz Avatar answered Jan 08 '23 21:01

jcalz