[英]How to specialize template type of a generic class in typescript?
是否可以在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
此类型为g
constructor
参数
constructor: { new(): IAType }
并没有真正施加约束, IAType
中的func()
必须以T
作为其参数类型。 唯一的约束是IAType extends IA<T>
,这意味着IAType
中的func
可以具有任何类型,只要它与func(arg: T)
兼容即可。 推论算法可能以最小类型{}
开头,验证func(arg: {})
与func(arg: T)
兼容并止于此。
对constructor
类型更加严格有助于:
interface IA<T> {
func(arg: T): void
}
function g<T, IAType extends IA<T>>(
constructor: { new(): IA<T> & IAType }
): (arg: T) => IAType {
const ins = new constructor();
return arg => {
ins.func(arg);
return ins;
}
}
class A implements IA<{ key: string }> {
func(arg: { key: string }) {
console.log(arg.key);
}
}
const t = g(A); // type of t is (arg: { key: string; }) => A
IA<T> & IAType
都是必需的。 如果只有IA<T>
,则将根据需要推断arg
类型,但是返回类型将仅为IA<T>
,而不是A
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.