【发布时间】:2018-08-18 13:36:33
【问题描述】:
是否可以在typescript的泛型函数中特化泛型类的模板类型?
假设我有一个通用接口和一个以接口构造函数为参数的函数:
interface IA<T> {
func(arg: T)
}
function g<T, IAType extends IA<T>>(
constructor: { new(): IAType }
): (arg: T) => IAType {
const ins = new constructor();
return arg => {
ins.func(arg);
return ins;
}
}
然后我提供类实现IA<T>,即
class A implements IA<{ key: string }> {
func(arg: { key: string }) {
console.log(arg.key);
}
}
const t = g(A); // type of t is (arg: {}) => A
如何编写函数 g 或类 A 以便函数 g 由于传入参数而可以专门化正确的模板类型?我想最终的t 的类型为(arg: {key: string}) => A
【问题讨论】:
标签: typescript typescript-generics