Typescript avoid generic type redundancy in function call

Viewed 22

I have a generic abstract class that takes a generic type T, which is the argument to a function called test.

abstract class AdvancedMarket<T>{
  abstract test(t: T): void
}

I then have a generic class that extends AdvancedMarkets and defines the test function.

class AMarket1<T> extends AdvancedMarket<T> {
  test(t: T): void {
    console.log(t + ": 1")
  }
}

Lastly, I have a generic function that takes 2 type arguments: V which is the type passed to the abstract class AdvancedMarket , and T which is the type of the abstract class AdvancedMarket.

function runATest<V, T extends AdvancedMarket<V>>(market: T, obj: V) {
  market.test(obj)
}

I know I can run the function without specifying the generic parameters, as they are inferred by the compiler:

const am1 = new AMarket1
runATest(am1, "Hello")

But let's suppose I would like to be explicit with the parameters, I would do something like:

runATest<string, AMarket2<string>>(am1, "Hello")

Now my question is, why do I have to be specific in marking the string type twice, <string, AMarket2<string>>, considering in the function declaration I already specify that V is the generic type passed to AdvancedMarket class: <V, T extends AdvancedMarket<V>>.

In other words, is there no way to avoid the redundancy of specifying the V type twice, by doing something like

runATest<string, AMarket2>(am1, "Hello")
runATest<AMarket2<string>>(am1, "Hello")

EDIT:

I might have another generic class which does not extend AdvancedMarket

class AMarket3<T> {
  test(t: T): void {
    console.log(t + "3")
  }
}

Thus I would do something like:

function runATest2<V, T extends {test(v: V): void}>(market: T, obj: V) {
  market.test(obj)
}

runATest2<string, AMarket3<string>>(am3, "hello")

Here I still would need to specify the string type twice.

0 Answers
Related