Typescript
catch문의 error 타입이 any 또는 unknown여야 하는 이유
2DC
2023. 8. 9. 11:11
Catch clause variable type annotation must be 'any' or 'unknown' if specified.
캐치문의 error 타입은 왜 any와 unknown이어야 하는 걸까?
개발하다가 아래와 같은 타입 에러를 만났다.
왜 캐치문의 에러는 any, unknown이어야 하는 걸까?
https://stackoverflow.com/questions/69021040/why-catch-clause-variable-type-annotation-must-be-any
Why Catch clause variable type annotation must be any?
I'm using yup to validate a form, and I encountered this type error while trying to make this catch work: Catch clause variable type annotation must be any or unknown if specified 1196 My Code: c...
stackoverflow.com
타입스크립트의 컴파일 과정에서는 catch에 어떤 에러가 도달할 지 알 수 없다.
따라서 에러에는 any나 unknown 타입을 할당해야 한다.
만약 정밀한 에러처리가 필요하다면
에러의 인스턴스를 확인한 후 에러 별 분기 처리 방법을 고려해보자.
try {
// .. 중략
} catch (error) {
if (error instanceof Error && error.name === "TokenExpiredError") {
return res.status(HttpStatusCode.UNAUTHORIZED).json({
statusCode: HttpStatusCode.UNAUTHORIZED,
message: "토큰이 만료되었습니다",
});
}
// .. 중략
}