TypeScript:数组赋值

时间:2016-07-18 20:01:45

标签: arrays typescript

我有一个带有对象属性的TypeScript类。此属性中的属性具有Array类型。我希望能够像在JavaScript中那样将FlowConnection类的实例添加到这些数组中,但以下代码会产生编译器错误:

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行,如下所示:

  

错误TS2322:输入&#39; FlowConnection&#39;不能分配给&#39; FlowConnection []&#39;。

尝试使用Array.push而不是分配到数组末尾的索引会产生更奇怪的结果:

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

错误TS2322:键入&#39; number&#39;不能分配给&#39; FlowConnection []&#39;。

我在这里缺少什么?

1 个答案:

答案 0 :(得分: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