0

As part of my model I have this class in TypeScript:

module App.Model {

    export class Unit {
            id: number;
            participantId: number;
            name: string;
            isProp: boolean;
        }
}

In the controller, I need a a hash with the id as key:

module App.Controllers {
    export class MyController {

        public units: App.Model.Unit[];

        populateDemoData() {
            this.units = {
                "1": { "id": 1, "participantId": 1, "name": "Testname", "isProp": true },
                "2": { "id": 2, "participantId": 1, "name": "Another name", "isProp": false }
            };
        }
    }
}

However, compiling the controller, I get the following error message:

Error 2 Cannot convert '{  }; [n: number]: App.Model.Unit; }' to ' }; [n: number]: App.Model.Unit; }' is missing property 'concat' from type 'App.Model.Unit[]'.

What am I doing wrong? And why is TypeScript asking for a concat property?

1 Answer 1

3

You defined units as an Array object, but assigned it a literal object. Just to clarify, a hash (a literal object) is not an array.

If all the IDs are an integer you can still use the array but it would be like this instead:

populateDemoData() {
    this.units = [];
    this.units[1] = { "id": 1, "participantId": 1, "name": "Testname", "isProp": true };
    this.units[2] = { "id": 2, "participantId": 1, "name": "Another name", "isProp": false };
}

Edit:

Ok, you have to define a hash table to do that, but you also need to make App.Model.Unit an interface that matches your JSON objects.

module App.Model {

    export interface Unit {
        id: number;
        participantId: number;
        name: string;
        isProp: boolean;
    }

    export interface UnitHashTable {
        [id: string]: Unit;
    }
}

module App.Controllers {

    export class MyController {

        public units: App.Model.UnitHashTable;

        populateDemoData() {
            this.units = {
                "1": { "id": 1, "participantId": 1, "name": "Testname", "isProp": true },
                "2": { "id": 2, "participantId": 1, "name": "Another name", "isProp": false }
            };
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your answer. How would I define the units as a hash? I meant hash! I was playing around with the definition, originally it was units: App.Model.Unit[] producing the same error. I update the question, sorry!
Looks great, thanks. I'll check later tonight when back online!

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.