【问题标题】:type validation for higher order components高阶组件的类型验证
【发布时间】:2017-10-12 15:08:18
【问题描述】:

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

Hoc1 = (superclass) => class extends superclass { ... }
class A { ... }
class B extends Hoc1(A) { ... }

我所说的类型检查是指使用两个最重要的实用程序中的任何一个:TypeScript 或 flow。

到目前为止,我已经在 TypeScript 中提出了以下 sn-p,

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

如果我这样写 mixin

const AMixin: (superclass) => typeof superclass & IAMixinConstructor =
  (superclass) => class extends superclass implements IAMixin {
    aMixedMethod() {}
  }

然后它将superclass 视为any 并且错误地错过了调用cMethod 的错误。

这似乎至少在 TypeScript 中是可能的,因为它们有例如Object.assign 正确地为 instances 工作。但是我需要相同类型的构造,但是对于类。

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

【问题讨论】:

标签: typescript ecmascript-6 mixins flowtype higher-order-components


【解决方案1】:

缺少的是将 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

【讨论】:

  • 我发现引入别名 type Class&lt;T&gt; = new () =&gt; T 并使用它可以使代码更具可读性。
猜你喜欢
  • 1970-01-01
  • 2019-07-25
  • 1970-01-01
  • 1970-01-01
  • 2019-05-31
  • 2019-06-26
  • 1970-01-01
  • 2019-07-21
  • 1970-01-01
相关资源
最近更新 更多