2014-02-12 2 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

감사합니다. 오늘 밤에 나중에 다시 확인해 볼게! –