包含对象数组的Typescript文字对象

时间:2015-04-03 11:48:15

标签: javascript knockout.js devexpress typescript phonejs

我的viewmodel中有一个工具栏对象,它会被渲染:

        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'>"
            }
        ]
    };

但是,当我尝试设置其中一个对象项的内容时,VS2013给出了一个奇怪的错误,如下所示:

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

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

我应该如何正确声明/初始化工具栏?

提前致谢

1 个答案:

答案 0 :(得分:2)

项目被推断为空对象{}。 您可以在接口中定义类型:

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

...或者您可以取消类型检查。

通过动态编程:

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

或者通过&#34;演员&#34;到any类型:

(<any>toolbar.items[1]).html(showCurrentDateTime());
相关问题