rory
rory

Reputation: 1438

Typescript literal object containing an array of objects

I have a toolbar object in my viewmodel and it does get rendered:

        var toolbar = {
        items: [
            {
                location: 'before',
                template: 'nav-button'
            },
            {
                location: "before",
                html: ko.observable(showCurrentDateTime()),
                tabIndex: 1
            },
            {
                location: "center",
                text: "title",
            },
            {
                location: "after",
                html: "<img src='../images/logo.png'>"
            }
        ]
    };

However, VS2013 gives me a weird error when I try to set the contents of one of the object items as follows:

toolbar.items[1].html(showCurrentDateTime());

error: The property 'html' does not exist on value of type '{}'

How should I declare/initalise toolbar correctly?

Thanks in advance

Upvotes: 1

Views: 2446

Answers (1)

Paleo
Paleo

Reputation: 23692

Items are inferred as empty objects {}. You can define the types in interfaces:

interface Item {
    location: string;
    template?: string;
    html?: Function;
    text?: string;
}
interface Toolbar {
    items: Item[];
}
var toolbar: Toolbar = {
    // ...
}
toolbar.items[1].html(showCurrentDateTime());

… Or you can cancel the type checking.

By dynamic programming:

toolbar.items[1]['html'](showCurrentDateTime());

Or by a "cast" to the type any :

(<any>toolbar.items[1]).html(showCurrentDateTime());

Upvotes: 2

Related Questions