에러처리

[Typescript] type assertion error

moonkey 2022. 7. 31. 15:35

타입스크립트에서 앞에서 조건문으로 값을 확인했음에도 type assertion을 쓰지 않으면 에러가 나는 경우가 있다. type assertion이 조금 폭력적인 방식이라 생각했지만 쓰지 않고는 코드가 너무 길어지거나 복잡해져서 type assertion을 쓸 수 밖에 없었다.🙃 

 

오늘 js로 작성한 heap 알고리즘을 typscript로 변경하는 도중 다음과 같은 에러가 발생했다.

while((this.heap[leftIndex] && this.heap[currentIndex] as number < this.heap[leftIndex] as number) ||
            (this.heap[rightIndex] && this.heap[currentIndex] as number < this.heap[rightIndex] as number)){}

 

위에 this.heap[leftIndex] as number를 작성하면서 위와 같이 오류가 발생했다. 알고보니 assertion을 사용할 때 사용할 대상과 함께 괄호를 만들어 주어야 했다. 다음과 같이 괄호로 묶어주니 오류가 해결된 것을 확인 하였다. 

while((this.heap[leftIndex] && (this.heap[currentIndex] as number) > (this.heap[leftIndex] as number)) ||
            (this.heap[rightIndex] && (this.heap[currentIndex] as number) > (this.heap[rightIndex] as number))){}