2016-07-18 5 views
0

개체 속성이있는 TypeScript 클래스가 있습니다. 이 속성의 속성에는 Array 유형이 있습니다. , 특정 컴파일러 오류가 위의 코드의 라인 (9)에서 발생TypeScript : 배열 할당

export class FlowComponent{ 
    protected connectionPoints = { 
     input: Array<FlowConnection>(), 
     output: Array<FlowConnection>() 
    } 

    addInput(newInput:FlowConnection):Array<FlowConnection>{ 
     var l = this.connectionPoints.input.length; 
     return this.connectionPoints.input[l] = newInput; 
} 

: 나는 자바 스크립트에서와 같이 이러한 배열 내 FlowConnection 클래스의 인스턴스를 추가 할 수있을 것으로 예상하지만, 다음 코드는 컴파일러 오류가 발생합니다 다음과 같이된다 :

return this.connectionPoints.input.push(newInput); 

error TS2322: Type 'number' is not assignable to type 'FlowConnection[]'.

대신 어레이의 끝에있는 인덱스를 할당하는 사항 Array.push 사용하려고

error TS2322: Type 'FlowConnection' is not assignable to type 'FlowConnection[]'.

가 짝수 낯선 결과를 얻을

여기에 무엇이 누락 되었습니까?

답변

2

return this.connectionPoints.input[l] = newInput; 배열의 인스턴스를 반환하지 않습니다. return this.connectionPoints.input.push(newInput); - 푸시를 수행 한 다음 반환하십시오! 참고로

this.connectionPoints.input.push(newInput); 
return this.connectionPoints.input; 

:

return this.connectionPoints.input[l] = newInput; //returns newInput 
return this.connectionPoints.input.push(newInput); //returns new array length 
+0

감사합니다! 첫 번째 컴파일러 오류가 훨씬 더 의미가 있습니다. 두 번째로, Array.push가 새 항목이 푸시 된 인덱스를 반환한다고 가정합니다. (당신 자신이 테스트하기에 충분히 쉽기 때문에 : P) – B1SeeMore

+0

@ B1SeeMore -'Array.push'는 배열의 새로운 길이를 반환한다고 믿습니다. – tymeJV

+0

글쎄, 나는 오늘 특히 기분이 좋습니다. : P 자바 스크립트 레퍼런스를 호스팅하는 사이트가 부족하지 않습니다. 방금 나가서 찾아봐야했습니다. 대답 해줘서 고마워! – B1SeeMore