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?

1
  • 2
    Take a look at your interface definition -- you're defining an array-like object, not an actual array. Commented Jan 24, 2015 at 13:26

1 Answer 1

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

2 Comments

Thanks al lot - it is working now. I'm really wondering because I didn't see this information on typescriptlang.org/Handbook#interfaces-array-types, there they do not put the [] after the interface definition ...
@mbader: it's actually under "basic types": typescriptlang.org/Handbook#basic-types-array

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.