Typescript 高阶组件的类型验证

Typescript 高阶组件的类型验证,typescript,ecmascript-6,mixins,flowtype,higher-order-components,Typescript,Ecmascript 6,Mixins,Flowtype,Higher Order Components,问题基本上是如何确保以典型的JavaScript方式实现的类型检查 Hoc1 = (superclass) => class extends superclass { ... } class A { ... } class B extends Hoc1(A) { ... } 我所说的类型检查是指使用两个最突出的实用程序中的任何一个:或 到目前为止,我已经用TypeScript编写了以下代码片段 interface IAMixin { aMixedMethod(): void } in

问题基本上是如何确保以典型的JavaScript方式实现的类型检查

Hoc1 = (superclass) => class extends superclass { ... }
class A { ... }
class B extends Hoc1(A) { ... }
我所说的类型检查是指使用两个最突出的实用程序中的任何一个:或

到目前为止,我已经用TypeScript编写了以下代码片段

interface IAMixin {
  aMixedMethod(): void
}
interface IAMixinConstructor {
  new(): IAMixin
}

const AHoc: <T>(superclass: T) => T & IAMixinConstructor = (superclass) =>
  class extends superclass implements IAMixin {
    aMixedMethod() {}
}

class A {
  aMethod() {}
}
class B extends AHoc(A) {
  bMethod() {}
}

const b = new B();

b.aMixedMethod(); // false-positive: incrorrectly reports as missing method
b.aMethod();
b.bMethod();
b.cMethod(); // this is correctly caught, though
然后它将
超类
视为
any
,而false则通过调用
cMethod
消极地错过一个错误

这似乎至少在TypeScript中是可能的,因为它们具有例如
对象。分配
正确地用于实例。但我需要同样的结构,只是为了课堂


或者我们需要像这样的类类型吗?

缺少的是将
AHoc
参数定义为类的构造函数函数类型,而不是实际实例和返回值的构造函数类型:

interface IAMixin {
  aMixedMethod(): void
}

const AHoc: <T>(superclass: new () => T) => new () => (T & IAMixin) =
    (superclass) => class extends superclass implements IAMixin {
        aMixedMethod() { }
    }

class A {
  aMethod() {}
}
class B extends AHoc(A) {
  bMethod() {}
}

const b = new B();

b.aMixedMethod(); // now good
b.aMethod();
b.bMethod();
b.cMethod(); // this is correctly caught
接口IAMixin{
aMixedMethod():void
}
常量AHoc:(超类:new()=>T)=>new()=>(T&IAMixin)=
(超类)=>类扩展超类实现IAMixin{
aMixedMethod(){}
}
甲级{
aMethod(){}
}
B类扩展AHoc(A){
b方法(){}
}
常数b=新的b();
b、 aMixedMethod();//现在好了
b、 aMethod();
b、 b方法();
b、 cMethod();//这是正确捕获的

有关推荐的模式,请参阅。我发现阅读新的TS功能更容易。我发现引入别名
type Class=new()=>T
并使用它可以使代码更具可读性。
interface IAMixin {
  aMixedMethod(): void
}

const AHoc: <T>(superclass: new () => T) => new () => (T & IAMixin) =
    (superclass) => class extends superclass implements IAMixin {
        aMixedMethod() { }
    }

class A {
  aMethod() {}
}
class B extends AHoc(A) {
  bMethod() {}
}

const b = new B();

b.aMixedMethod(); // now good
b.aMethod();
b.bMethod();
b.cMethod(); // this is correctly caught