1

我的视图模型中有一个工具栏对象,它确实被渲染了:

        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 '{}'

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

提前致谢

4

1 回答 1

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());

或通过“强制转换”类型any

(<any>toolbar.items[1]).html(showCurrentDateTime());
于 2015-04-03T12:02:35.817 回答