【问题标题】:Typescript literal object containing an array of objects包含对象数组的打字稿文字对象
【发布时间】:2015-04-03 11:48:14
【问题描述】:

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

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

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

提前致谢

【问题讨论】:

    标签: javascript knockout.js devexpress typescript phonejs


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-05-02
      • 2020-05-16
      • 2023-02-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2021-11-02
      • 1970-01-01
      • 2020-06-22
      相关资源
      最近更新 更多