0
votes

I have a TypeScript class with an object property. The properties inside this property have the type Array. I expected to be able to add instances of my FlowConnection class to these arrays like I would in JavaScript, but the following code produces a compiler error:

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;
}

The specific compiler error occurs on line 9 of the code above, and is as follows:

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

Trying to use Array.push instead of assigning to the index at the end of the array yields an even stranger result:

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

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

What am I missing here?

1

1 Answers

2
votes

return this.connectionPoints.input[l] = newInput; doesn't return an instance of an Array - nor does return this.connectionPoints.input.push(newInput); - do the push, then return!

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

For reference:

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