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?

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.