【问题标题】:Implementing an interface in Javascript using flow-runtime使用流运行时在 Javascript 中实现接口
【发布时间】:2017-06-22 23:53:15
【问题描述】:

我正在使用flow-runtime 插件babel 来生成动态类型检查的javascript 代码。以下是我正在使用的工作流程

  • 编写静态javascript代码(带流注解)

  • 使用 babel 编译此代码以将流注解转换为类型检查代码

  • 在 node.js 中运行这个编译后的代码

以下工作流程使我能够编写打字稿类型代码,但只在我想要的地方进行类型检查。

所以,既然我们了解了我在做什么,让我解释一下我想要实现的目标

我基本上需要构建一个名为Interface 的类,它会完全按照听起来的样子。这个类将由应该是接口的类扩展,然后由其他类扩展。像这样的东西:

class Interface() {
    constructor() {
        ...
    }

    // interface superclass, supposed to be extended by all interfaces
    // this class will provide all the utility methods required 
    // by an interface, such as validating the implementation of the 
    // interface, ...

    validateInterfaceImplementation() {
        ...
    }
}

// interface definition
class FooInterface extends Interface {
    constructor() {
        super();
        ...
    }
}

// actual class, that will implement the "FooInterface" interface
class Foo extends FooInterface {
    constructor() {
        super();
        ...
    }
}

现在,我想严格执行FooInterface。这意味着我想要一种方法来定义 FooInterface interface 期望实现的所有方法,并验证所有这些方法是否已由 Foo 类实现。

我尝试过的看起来像这样

// interface.js
// @flow-runtime
class Interface<T> {
    constructor(t: T) {
        (this: T); // let flow validate that the interface is implemented
    }
}

// FooInterface.js
// @flow-runtime
type foInterface = {
    bar(param: string): number;
}

class FooInterface extends Interface<fooInterface> {
    constructor() {
        super(fooInterface);
    }
}

// Foo.js
// @flow-runtime
class Foo extends FooInterface {

}

new Foo(); // should throw an error, because the interface is not implemented
           // (the function bar is not defined)

我在使用这种方法时遇到了多个问题

  • 我不确定如何实现泛型类Interface&lt;T&gt;。 in think我的实现不正确,编译出来的babel代码也报错了,但是不知道怎么弄。
  • 我什至不确定这种方法是否有效,或者这是否是解决此问题的最佳方法。

欢迎任何帮助。在此先感谢:)

【问题讨论】:

    标签: javascript inheritance interface babeljs


    【解决方案1】:

    从 flow-runtime 0.5.0 开始,您可以将 Flow 的 implements 关键字与 Flow 接口结合使用。我认为这将为您提供所需的东西,而无需创建具体的类:

    // @flow
    // @flow-runtime
    interface IPoint<T> {
      x: T;
      y: T;
    }
    
    interface IJSON {
      toJSON (): any;
    }
    
    class Point implements IPoint<number>, IJSON {
      x: number = 123;
      y: number = 456;
      toJSON () {
         return {x: this.x, y: this.y};
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      相关资源
      最近更新 更多