1

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?

JJJ
  • 32,902
  • 20
  • 89
  • 102
developer82
  • 13,237
  • 21
  • 88
  • 153

3 Answers3

4

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
bob
  • 91
  • 1
  • 13
Fenton
  • 241,084
  • 71
  • 387
  • 401
2

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.

nightlyop
  • 7,675
  • 5
  • 27
  • 36
0

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