B1SeeMore B1SeeMore - 2 months ago 8
TypeScript Question

TypeScript: Array Assignment

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>()

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?


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!

return this.connectionPoints.input;

For reference:

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