일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- AppleDeveloperAcademy
- git
- SWIFT
- error
- frontend
- JavaScript
- react
- globalcommunity
- tshaped
- ios
- 프로그래머스
- TypeScript
- 알고리즘
- swiftUI
- iOSDeveloper
- velog
- NextJs
- 프론트엔드
- 코딩테스트
- Front-end
- 회고
- 프로젝트
- 코드트리
- UIKit
- Xcode
- 코드트리챌린지
- Apple Developer Academy
- react-query
- 코딩테스트실력진단
- 자바스크립트
Archives
- Today
- Total
Moon Work
[Typescript] type assertion error 본문
타입스크립트에서 앞에서 조건문으로 값을 확인했음에도 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))){}
'에러처리' 카테고리의 다른 글
[CORS] Cors를 처리해도 Cors 에러가 나는 경우(with Credentials) (0) | 2022.12.28 |
---|---|
에러처리: [eslint] Failed to load plugin 'jsx-a11y' declared in 'package.json (0) | 2022.12.03 |
[Typescript] React props key error (0) | 2022.08.10 |
[React + Typescript] IntrinsicAttributes 에러 (0) | 2022.08.09 |
[Typescript] Cannot find name 'console' 에러 (0) | 2022.07.27 |