2014-02-12 79 views
0

由於我的模型的一部分,我有這個類打字稿:填充類[]用JSON在打字稿

module App.Model { 

    export class Unit { 
      id: number; 
      participantId: number; 
      name: string; 
      isProp: boolean; 
     } 
} 

在控制器中,我需要用id AA哈希關鍵:

module App.Controllers { 
    export class MyController { 

     public units: App.Model.Unit[]; 

     populateDemoData() { 
      this.units = { 
       "1": { "id": 1, "participantId": 1, "name": "Testname", "isProp": true }, 
       "2": { "id": 2, "participantId": 1, "name": "Another name", "isProp": false } 
      }; 
     } 
    } 
} 

然而,編譯器,我得到了以下錯誤消息:

 
Error 2 Cannot convert '{ }; [n: number]: App.Model.Unit; }' to ' }; [n: number]: App.Model.Unit; }' is missing property 'concat' from type 'App.Model.Unit[]'.

我在做什麼錯了嗎?爲什麼TypeScript要求concat屬性?

回答

3

您將units定義爲Array對象,但爲其分配了一個文字對象。爲了澄清,散列(一個文字對象)不是一個數組。

如果所有的ID是一個整數,你仍然可以使用數組,但它會是這樣,而不是:

populateDemoData() { 
    this.units = []; 
    this.units[1] = { "id": 1, "participantId": 1, "name": "Testname", "isProp": true }; 
    this.units[2] = { "id": 2, "participantId": 1, "name": "Another name", "isProp": false }; 
} 

編輯:

好吧,你必須定義一個哈希表來做到這一點,但你也需要使App.Model.Unit與你的JSON對象匹配的接口。

module App.Model { 

    export interface Unit { 
     id: number; 
     participantId: number; 
     name: string; 
     isProp: boolean; 
    } 

    export interface UnitHashTable { 
     [id: string]: Unit; 
    } 
} 

module App.Controllers { 

    export class MyController { 

     public units: App.Model.UnitHashTable; 

     populateDemoData() { 
      this.units = { 
       "1": { "id": 1, "participantId": 1, "name": "Testname", "isProp": true }, 
       "2": { "id": 2, "participantId": 1, "name": "Another name", "isProp": false } 
      }; 
     } 
    } 
} 
+0

感謝您的回答。我如何將單位定義爲散列?我的意思是哈希!我正在玩這個定義,原來是'units:App.Model.Unit []'產生了同樣的錯誤。我更新了這個問題,對不起! –

+1

好吧,我編輯了我的答案,我希望這有助於。 – thoughtrepo

+0

看起來不錯,謝謝。我今晚會在網上查詢 –