rockson
rockson

Reputation: 63

Constructor as parameter: infer class's generic into function

How to make the typescript compiler infer the right type in this example?

interface A<T> {
  do(param: T): void
}

class A2 implements A<string>{
  do(param){}
}

function createA<T>(constr: new () => A<T>, param: T){}

createA(A2, "")

Here it won't compile and T is inferred the type any

Upvotes: 1

Views: 62

Answers (2)

Alex Wayne
Alex Wayne

Reputation: 186984

You need to make the class generic as well so that you can tell typescript the interface parameter and the function argument are of the same type, without repeating yourself:

class A2<T extends string> implements A<T>{
  go(param: T) {
     param.split('') // string method is allowed here
  }
}

Playground

Upvotes: 2

andr&#232;s coronado
andr&#232;s coronado

Reputation: 170

I think you have to make it do(param: string) if you implement the A<string> interface with the A2 Class.If you try to give it any other type you should get an error, for example if you use do(param: number) in A<string> implementation you get

Property 'do' in type 'A2' is not assignable to the same property in base type 'A<string>'.
  Type '(param: number) => void' is not assignable to type '(param: string) => void'.
    Types of parameters 'param' and 'param' are incompatible.
      Type 'string' is not assignable to type 'number'

Upvotes: 1

Related Questions