2015-04-03 157 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());