2

Using Javascript with Typescript (v1.4.1) I have a custom type as follows:

interface WordDataForQuestion {
    question : {
        id : number;
        vocab : string;
        comment : string;
    };
    possibleAnswers : {
        [index : number] : {
            id : number;
            vocab : string;
            comment : string;
        }
    };
}

Now I want to push an element in the array possibleAnswers

nextWordData.possibleAnswers.push(
    {
        id : vocabs[index].id,
        vocab : vocabs[index].voc_t,
        comment : vocabs[index].com_t
    }
);

but it gives me the following error:

exercise.ts(69,42): error TS2339: Property 'push' does not exist on type '{ [index: number]: { id: number; vocab: string; comment: string; }; }'.

I don't understand what is wrong - possibleAnswers should be a JavaScript array here which supports the push-operation. Am I not right?

Mathias Bader
  • 2,904
  • 5
  • 32
  • 52

1 Answers1

3

You are almost there. You did define it as an object with an indexer. Not as an array, see example below

possibleAnswers : {
        id : number;
        vocab : string;
        comment : string;
}[];
Dick van den Brink
  • 11,099
  • 3
  • 28
  • 40
  • Thanks al lot - it is working now. I'm really wondering because I didn't see this information on http://www.typescriptlang.org/Handbook#interfaces-array-types, there they do not put the [] after the interface definition ... – Mathias Bader Jan 24 '15 at 13:32
  • 1
    @mbader: it's actually under "basic types": http://www.typescriptlang.org/Handbook#basic-types-array – Qantas 94 Heavy Jan 24 '15 at 14:28