developer82
developer82

Reputation: 13733

TypeScript push not available on interface array

I'm trying to define an interface that is an array as explained here: http://www.typescriptlang.org/Handbook#interfaces-array-types and then push items to it. The problem is that TypeScript says that push doesn't exists.

I have tried the following example in the playground:

interface StringArray {
   [index: number]: string;
}

var myArray: StringArray;
myArray = ["Bob", "Fred"];

myArray.push('Barney'); // <- push doesn't exist ??

Is that interface not a regular array?

Upvotes: 1

Views: 5995

Answers (3)

Michael Nchendia
Michael Nchendia

Reputation: 1

There is a simple way to bypass that issue. You just use the array length property and assign the new values to the end of the array.

interface StringArray {
   [index: number]: string;
}
var myArray: StringArray;
myArray = ["Bob", "Fred"];

myArray[myArray.length] = 'Barney'; 

Upvotes: 0

Fenton
Fenton

Reputation: 251242

It can be just like a regular array, if you tell the compiler it is:

interface StringArray extends Array<string> {
   [index: number]: string;
}

By default, your StringArray only has the members you define. There are some cases where an array-like structure doesn't support all array methods, even though it has an indexer like an array - but in your case, extending the Array interface will solve your issue.

Full example:

interface StringArray extends Array<string> {
   [index: number]: string;
}

var myArray: StringArray;
myArray = ["Bob", "Fred"];

myArray.push('Barney'); // now ok

Upvotes: 4

nightlyop
nightlyop

Reputation: 7975

I usually don't define an interface that is an array but define an array which has the interface as type:

var myArray: string[];
myArray = ["Bob", "Fred"];
myArray.push('Barney');

I like this more because it is easier but to be honest, I don't know if there is a difference in functionallity.

Upvotes: 2

Related Questions