构造函数作为参数:将类的泛型推断为函数

问题描述 投票:1回答:2

在此示例中,如何使打字稿编译器推断正确的类型?

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, "")

在这里它不会编译,并且T被推断为任何类型

typescript
2个回答
2
投票
您还需要使类具有通用性,以便您可以告诉Typescript接口参数和function参数是同一类型,而无需重复自己的内容:

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

Playground    

1
投票
[我认为如果使用do(param: string)类实现A<string>接口,则必须将其设置为A2。如果尝试为其提供任何其他类型,则应该会收到错误消息,例如,如果使用do(param: number)A<string>实现中,您会得到

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'

© www.soinside.com 2019 - 2024. All rights reserved.