7

TypeScriptで遊んでいて、いくつかの機能的なミックスイン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);

上記のコードは正常に機能しますが、のような混合メソッドの1つを使用しようとするとコンパイルされません(new Model()).set('foo', 'bar')

私はこれを回避することができます

  1. interfaceミックスインの宣言を追加する
  2. 宣言でダミーget///メソッドをset宣言するontriggerModel

ダミー宣言を回避するクリーンな方法はありますか?

4

4 に答える 4

12

interfacesメソッドを使用してmixin にアプローチする 1 つの方法を次に示しstatic create()ます。インターフェイスは多重継承をサポートしているため、ミックスインの を再定義するinterfaces必要がなくなり、メソッドが のインスタンスをとしてstatic create()返すように処理します(コンパイラの警告を抑制するには、キャストが必要です)。すべてを複製する必要があります。 whichのメンバー定義は最悪ですが、現在のバージョンの TypeScript で必要なものを実現する最もクリーンな方法のようです。 Model()IModel<any>ModelIModel

編集: ミックスインをサポートするためのもう少し単純なアプローチを特定し、それらを定義するためのヘルパー クラスも作成しました。詳細はこちら.

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');
于 2012-10-04T05:46:17.057 に答える
3

これを行う最もクリーンな方法は、依然として double 型宣言が必要ですが、mixin をモジュールとして定義することです。

module Mixin {
    export function on(test) {
        alert(test);
    }
};

class TestMixin implements Mixin {
    on: (test) => void;
};


var mixed = _.extend(new TestMixin(), Mixin); // Or manually copy properties
mixed.on("hi");

インターフェイスを使用する代わりに、クラスでハックすることもできます (ただし、複数の継承があるため、ミックスイン用の共通インターフェイスを作成する必要があります)。

var _:any;
var __mixes_in = _.extend; // Lookup underscore.js' extend-metod. Simply copies properties from a to b

class asSettable {
    getx(key:string) { // renamed because of token-clash in asEventAndSettable
        return this[key];
    }
    setx(key:string, value) {
        this[key] = value;
        return this;
    }
}

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

class asEventAndSettable {
   // Substitute these for real type definitions
   on:any;
   trigger:any;
   getx: any;
   setx: any;
}

class Model extends asEventAndSettable {
    /// ...
}

var m = __mixes_in(new Model(), asEventable, asSettable);

// m now has all methods mixed in.

Steven の回答にコメントしたように、ミックスインは本当に TypeScript の機能であるべきです。

于 2012-10-04T06:04:51.063 に答える
1

1つの解決策は、typescriptクラスシステムを使用せず、キーワード「new」に加えて、タイプとインターフェイスのシステムのみを使用することです。

    //the function that create class
function Class(construct : Function, proto : Object, ...mixins : Function[]) : Function {
        //...
        return function(){};
}

module Test { 

     //the type of A
    export interface IA {
        a(str1 : string) : void;
    }

    //the class A 
    //<new () => IA>  === cast to an anonyme function constructor that create an object of type IA, 
    // the signature of the constructor is placed here, but refactoring should not work
    //Class(<IA> { === cast an anonyme object with the signature of IA (for refactoring, but the rename IDE method not work )
    export var A = <new () => IA> Class(

        //the constructor with the same signature that the cast just above
        function() { } ,

        <IA> {
            //!! the IDE does not check that the object implement all members of the interface, but create an error if an membre is not in the interface
            a : function(str : string){}
        }
    );


    //the type of B
    export interface IB {
        b() : void;
    }
    //the implementation of IB
    export class B implements IB { 
        b() { }
    }

    //the type of C
    export interface IC extends IA, IB{
        c() : void;
        mystring: string;
    }

     //the implementation of IC
    export var C = <new (mystring : string) => IC> Class(

        //public key word not work
        function(mystring : string) { 

            //problem with 'this', doesn't reference an object of type IC, why??
            //but google compiler replace self by this !!
            var self = (<IC> this);
            self.mystring = mystring;
        } ,

        <IC> {

            c : function (){},

            //override a , and call the inherited method
            a: function (str: string) {

                (<IA> A.prototype).a.call(null, 5);//problem with call and apply, signature of call and apply are static, but should be dynamic

                //so, the 'Class' function must create an method for that
                (<IA> this.$super(A)).a('');
            }

        },
        //mixins
        A, B
    );

}

var c = new Test.C('');
c.a('');
c.b();
c.c();
c.d();//ok error !
于 2013-01-22T23:34:56.203 に答える