我们可以用TypeScrip编写自己的方法来扩展已知的类型class A
.扩展后,新类型的实例将具有正确的类型,并且可以通过类型系统访问字段a
和e
:
class A {
a = "a";
}
function extend(originalType: typeof A){
return class extends originalType {
e = "e"
}
}
const ExtA = extend(A);
const extA = new ExtA();
console.log(extA.a, extA.e); // both .a and .e are accessible.
如果我们try 使用相同的函数声明来扩展子类class B
,显然,字段b
在类型系统中将不可用:
// continued...
class B extends A {
b = "b";
}
const ExtB = extend(B);
const extB = new ExtB();
console.log(extB.a, extB.b, extB.e); // Property 'b' does not exist on type '(Anonymous class)'
这是TSplayground link
我曾try 编写一个extend2
和extend3
方法,可以在A
的任何子类上工作,但没有成功.
这是两次try ,使用泛型,都会导致TS编译错误:
// A mixin class must have a constructor with a single rest parameter of type 'any[]'.
function extend2<T extends typeof A>(subclassType: T) {
return class extends subclassType {
e = "e"
}
}
// Class '(Anonymous class)' incorrectly extends base class 'T'.
'(Anonymous class)' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'A'
function extend3<T extends A>(subclassType: new (...args: any[]) => T) {
return class extends subclassType {
e = "e"
}
}
在这一点上,有没有办法在TypeScrip(5.3.3版)中实现这一点?