2015-04-03 244 views
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 '{}' 

我该如何正确声明/ initalise工具栏?

在此先感谢

回答

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