2016-07-18 7 views
0

私はオブジェクトプロパティを持つTypeScriptクラスを持っています。このプロパティ内のプロパティの型はArrayです。私はJavaScriptで希望のように、これらの配列に私のFlowConnectionクラスのインスタンスを追加することができると期待が、次のコードは、コンパイラエラーを生成します。TypeScript:配列の割り当て

export class FlowComponent{ 
    protected connectionPoints = { 
     input: Array<FlowConnection>(), 
     output: Array<FlowConnection>() 
    } 

    addInput(newInput:FlowConnection):Array<FlowConnection>{ 
     var l = this.connectionPoints.input.length; 
     return this.connectionPoints.input[l] = newInput; 
} 

特定のコンパイラエラーが上記のコードの行9で発生し、以下のようである:

return this.connectionPoints.input.push(newInput); 

error TS2322: Type 'number' is not assignable to type 'FlowConnection[]'.

error TS2322: Type 'FlowConnection' is not assignable to type 'FlowConnection[]'.

のArray.pushを使用しようとする代わりにアレイの端部にインデックスを割り当てても他人の結果をもたらします

私はここで何が欠けていますか?

答えて

2

return this.connectionPoints.input[l] = newInput;配列のインスタンスを返さない - return this.connectionPoints.input.push(newInput); - プッシュを行い、その後に戻ります!参考のため

this.connectionPoints.input.push(newInput); 
return this.connectionPoints.input; 

return this.connectionPoints.input[l] = newInput; //returns newInput 
return this.connectionPoints.input.push(newInput); //returns new array length 
+0

ありがとう!最初のコンパイラのエラーは今よりはるかに意味があります。 2番目の例では、Array.pushは新しい項目がプッシュされたインデックスを返します。 (私自身のためにテストするのに十分なので、あなたが望む場合を除いて答えを求められないように気をつけないでください:P) – B1SeeMore

+0

@ B1SeeMore - 私は 'Array.push'が配列の新しい長さを返すと信じています – tymeJV

+0

今日は特に明るく感じます。 :P JavaScriptリファレンスをホスティングしているサイトの不足はありません。回答ありがとうございます! – B1SeeMore