我正在玩TypeScript,我有几个functional mixins,Eventable
和Settable
,我想混入一个Model
类(假装它像Backbone.js模型):上述TypeScript中的Mixins
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')
一个不会编译。
我可以解决此通过
- 添加
interface
声明的混入 - 宣布在
Model
声明
虚拟get
/set
/on
/trigger
方法有没有干净的方式围绕虚拟声明?
可能相关的解决方案,在[微软/打字稿#2919]来解决这个(https://github.com/Microsoft/TypeScript/issues/2919#issuecomment-173384825) – mucaho