首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >高阶组件的类型验证

高阶组件的类型验证
EN

Stack Overflow用户
提问于 2017-05-13 10:52:24
回答 1查看 127关注 0票数 0

问题基本上是如何确保使用高阶元件以典型的JavaScript方式实现类型检查。

代码语言:javascript
复制
Hoc1 = (superclass) => class extends superclass { ... }
class A { ... }
class B extends Hoc1(A) { ... }

通过类型检查,我的意思是使用两个最突出的实用程序:TypeScript

到目前为止,我已经在TypeScript中找到了以下代码片段,

代码语言:javascript
复制
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

如果我用这种方式写混音

代码语言:javascript
复制
const AMixin: (superclass) => typeof superclass & IAMixinConstructor =
  (superclass) => class extends superclass implements IAMixin {
    aMixedMethod() {}
  }

然后,它认为superclassany,而false-负面地忽略了cMethod调用的错误。

这似乎至少在TypeScript中是可能的,因为他们有正确的Object.assign为实例工作。但我需要的是同类型的建筑,除了上课。

还是需要像Ruby类这样的类类型?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-13 12:16:40

所缺少的是将AHoc参数定义为类的构造函数类型,而不是实际实例,对于返回的值也是如此:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43952253

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档