2017-09-12 18 views
0

私はCandlesというクラスとCandleというクラスを持っています。 Candlesは、Candleの配列を含むプロパティlistを持っています。Typescript:クラスからアイテムを取得するために配列表記を使用

class Candles 
{ 
    public list: Array<Candle>; 
} 

class Candle 
{ 
    public date: number; 
    public high: number; 
    public low: number; 
    public open: number; 
    public close: number; 
    public volume: number; 
} 

私はlistCandlesクラスにカプセル化します。例えば、

const candles = new Candles(); 
candles[3] === candles.list[3]; 

私はcandles[3]は、私はまた、マップを使用したいcandles.list[3]

を返すようにしたいです。例:

candles.map(function(candle: Candle) { 
    console.log(candle.high); 
}); 

答えて

1

で説明したように、標準配列を拡張あなたはES6 Proxyを使用して内側のリストへの呼び出しをインターセプトし、前方にすることができます

class Candles { 
    public list: Candle[] = []; 

    constructor() { 
    return new Proxy(this, { 
     get(target, propertyKey) { 
     console.log('getting ', propertyKey); 
     if (propertyKey in target) { 
      console.log('own property'); 
      return target[propertyKey] 
     } 

     console.log('forward to inner list'); 
     const property = target.list[propertyKey]; 
     if (typeof property === "function") { 
      return property.bind(target.list); 
     } 

     return property; 
     } 
    }); 
    } 
} 

Candles缶コンパイラに通知するには定義以下のArrayアドオンとして使用すること:

interface Candles extends Array<Candle> { } 

そして今、すべての配列グッズ(例えばpushforeachmapは...)Candlesに適用することができます。

const candles = new Candles(); 
candles.push({ low: 1 } as Candle); 

console.log(candles[0] === candles.list[0]); //true 
candles.forEach(c => console.log(c)); 

Demo遊び場に。

1

Javascriptがこのいずれかをサポートしていないので、あなたは活字体でのインデックス操作の動作を変更することはできません。あなたはどうする可能性は型tahtを作成しているこのquestion

0

は、ここに私がやったことだ:

class Candles extends Array<Candle> 
{ 
    constructor(candles: Array<Candle.Data>) { 
    super(...candles.map((candle) => new Candle(candle as Candle.Data))); 
    Object.setPrototypeOf(Candles, Object.assign(Array.prototype, Candles.prototype)); 
    } 
} 

私はlistを取り除くだけArray<Candle>を拡張しました。私はCandlesの方法と共にArrayメソッドを使用するためにObject.setPrototypeOf(Candles, Object.assign(Array.prototype, Candles.prototype));を追加しました

関連する問題