在此示例中,如何使打字稿编译器推断正确的类型?
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被推断为任何类型
class A2<T extends string> implements A<T>{
go(param: T) {
param.split('') // string method is allowed here
}
}
Playground
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'