【发布时间】:2012-09-25 01:13:32
【问题描述】:
我正在玩 TypeScript,我有几个 functional mixins、Eventable 和 Settable,我想将它们混入 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') 等混合方法之一,则无法编译。
我可以解决这个问题
- 为 mixins 添加
interface声明 - 在
Model声明中声明虚拟get/set/on/trigger方法
有没有绕过虚拟声明的干净方法?
【问题讨论】:
-
可能与Microsoft/TypeScript#2919相关的解决方案@
标签: mixins typescript