[에러] e.message

옥수수의 코딩이야기·2023년 2월 5일
0

에러

목록 보기
9/18
post-thumbnail

문제: e.message 사용시 Object is of type 'unknown'.ts 발생

try {
  // your logic
} catch (error) {
  // error logging
  console.log(error.message)
}

이유: error object가 unknown type으로 정의됨
해결방안 4가지
1. 버전 낮추기
2. any 타입으로 변경하기

try {
  // your logic
} catch (error: any) {
  // error logging
  console.log(error.message)
}
  1. 새로운 Error 타입을 만들기
interface SystemError {
  code: string;
  message: string;
}

try {
  // your logic
} catch (error) {
  const err = error as SystemError; // type assertion으로 error 타입을 확실하게 정해준다.
  if (err.code === 'ENOENT") {
      console.log('Files not exists')
  }
  // error logging
  console.log(error.message)
}

참고
https://velog.io/@devstefancho/typescript-Object-is-of-type-unknown.ts2571-error-object
https://stackoverflow.com/questions/69422525/in-typescript-try-catch-error-object-shows-object-is-of-type-unknown-ts25

profile
프론트엔드 공부중 기억은 블로그가 대신합니다.

0개의 댓글