2013-02-04 3 views
27

I 타이프에서 다음과 같은 클래스가 :TypeScript에서 배열을 초기화하고 초기화하고 채우는 방법은 무엇입니까?

class bar { 
    length: number; 
} 

class foo { 
    bars: bar[] = new Array(); 
} 

을 그리고 내가 가진 :

var ham = new foo(); 
ham.bars = [ 
    new bar() {   // <-- compiler says Expected "]" and Expected ";" 
     length = 1 
    } 
]; 

타이프에 있다고 할 수있는 방법이 있나요?

class bar { 
    length: number; 

    private ht: number; 
    height(h: number): bar { 
     this.ht = h; return this; 
    } 

    constructor(len: number) { 
     this.length = len; 
    } 
} 

class foo { 
    bars: bar[] = new Array(); 
    setBars(items: bar[]) { 
     this.bars = items; 
     return this; 
    } 
} 

그래서 당신이 아래를 초기화 할 수 있습니다 :

var ham = new foo(); 
ham.setBars(
    [ 
     new bar(1).height(2), 
     new bar(3) 
    ]); 
+0

TypeScript에서 C#과 비슷한 개체 이니셜 라이저를 사용하면 정말 유용 할 것입니다. '[{length : 1}]'은 bar의 인스턴스가 아니지만 지원된다면 new bar() {length = 1}은 bar의 인스턴스가됩니다. 어쩌면 우리는 이것에 대한 제안을해야할까요? – orad

답변

30

가 외설

UPDATE

나는 자체를 반환하는 일련의 방법을함으로써 다른 솔루션을 함께했다 JavaScript 나 TypeScript의 객체와 같은 필드 초기화 구문.

옵션 1 :

class bar { 
    // Makes a public field called 'length' 
    constructor(public length: number) { } 
} 

bars = [ new bar(1) ]; 

옵션 2 :

interface bar { 
    length: number; 
} 

bars = [ {length: 1} ]; 
+3

을 사용하면 더 명확하고 타입 안전합니다.'bars : bar [] = [{length : 1}]' – Patrice

+0

클래스를 정의하지 않고이를 수행 할 수있는 방법이 있습니까? – blackiii

+0

질문은 클래스의 배열을 초기화하는 방법에 관한 것입니다. 클래스를 사용하지 않고 클래스의 배열을 초기화하는 방법은 없습니다. 문제 링크는 –

14

당신이 정말로라는 이름의 매개 변수가 플러스 객체가 클래스의 인스턴스가 될 수 있도록하려면, 다음을 수행 할 수 있습니다

class bar { 
    constructor (options?: {length: number; height: number;}) { 
     if (options) { 
      this.length = options.length; 
      this.height = options.height; 
     } 
    } 
    length: number; 
    height: number; 
} 

class foo { 
    bars: bar[] = new Array(); 
} 

var ham = new foo(); 
ham.bars = [ 
    new bar({length: 4, height: 2}), 
    new bar({length: 1, height: 3}) 
]; 

here은 타이프 스크립트 이슈 트래커상의 관련 항목입니다.

+0

+1입니다. 이니셜 라이저 값을 선택적으로 만들 수도 있습니다 : 'options? : {길이 ?: 번호; height ?: number;}' –

관련 문제