TypeScript 中的混合

标签 mixins typescript

我正在使用 TypeScript,我有几个 functional mixinsEventableSettable,我想将其混合到 Model 类中(假装它类似于 Backbone.js 模型):

function asSettable() {
  this.get = function(key: string) {
    return this[key];
  };
  this.set = function(key: string, value) {
    this[key] = value;
    return this;
  };
}

function asEventable() {
  this.on = function(name: string, callback) {
    this._events = this._events || {};
    this._events[name] = callback;
  };
  this.trigger = function(name: string) {
    this._events[name].call(this);
  }
}

class Model {
  constructor (properties = {}) {
  };
}

asSettable.call(Model.prototype);
asEventable.call(Model.prototype);

上面的代码工作正常,但如果我尝试使用其中一种混合方法,如 (new Model()).set('foo', 'bar'),则无法编译.

我可以解决这个问题

  1. 为 mixins 添加 interface 声明
  2. Model 中声明虚拟 get/set/on/trigger 方法> 声明

是否有绕过虚拟声明的干净方法?

最佳答案

这是使用 interfaces 处理混入的一种方法和一个 static create()方法。接口(interface)支持多重继承,因此您不必重新定义 interfaces为你的 mixins 和 static create()方法负责返回一个 Model() 的实例。作为IModel (需要 <any> 转换才能抑制编译器警告。)您需要复制 Model 的所有成员定义。在 IModel这很糟糕,但它似乎是在当前版本的 TypeScript 中实现你想要的最干净的方法。

编辑:我已经确定了一种稍微简单的方法来支持混入,甚至创建了一个辅助类来定义它们。详情可查over here .

function asSettable() {
  this.get = function(key: string) {
    return this[key];
  };
  this.set = function(key: string, value) {
    this[key] = value;
    return this;
  };
}

function asEventable() {
  this.on = function(name: string, callback) {
    this._events = this._events || {};
    this._events[name] = callback;
  };
  this.trigger = function(name: string) {
    this._events[name].call(this);
  }
}

class Model {
  constructor (properties = {}) {
  };

  static create(): IModel {
      return <any>new Model();
  }
}

asSettable.call(Model.prototype);
asEventable.call(Model.prototype);

interface ISettable {
    get(key: string);
    set(key: string, value);
}

interface IEvents {
    on(name: string, callback);
    trigger(name: string);
}

interface IModel extends ISettable, IEvents {
}


var x = Model.create();
x.set('foo', 'bar');

关于TypeScript 中的混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12719844/

相关文章:

flutter 如何在 GetView<Controller> 类中实现动画

c++ - 即时推导

node.js - 无法通过express/heroku查看Angular应用程序?

javascript - 构造函数作为对象键

javascript - 如何折叠面板?

javascript - 用于 React-Native 应用程序的平台特定 ios/android typescript 文件的相对导入

ruby - Ruby 中的多重继承

django - 由使用 mixin 动态修改创建的集合

string - LESS mixin 作为函数参数

typescript - ts-jest - 运行 jest 时,从类型 (.d.ts) 中声明 const 值未定义