[typescript] --useUnknownInCatchVariables

Yeonjoo Yoo·2022년 2월 2일
0

TIL

목록 보기
6/12
tsconfig.json 옵션 중 "strict": true 시, try-catch 에 catch 블록에서 오류가 발생했다. 
타입이 'Error'나 'any'일 것으로 생각했는데, 'unknown' 타입이여서, error.message 가 문제가 되었다. 
해결 방법을 찾던 중 "--useUnknownInCatchVariables"에 대해 알게 되어 정리하게 되었다.

strict (tsconfig.json)

  • default : false
  • tsconfig.json에 strict 옵션의 값이 true 인 경우, 아래 옵션 모두 true
    1. alwaysStrict
    2. strictNullChecks
    3. strictBindCallApply
    4. strictFunctionTypes
    5. strictPropertyInitialization
    6. noImplicitAny
    7. noImplicitThis
    8. useUnknownInCatchVariables

--useUnknownInCatchVariables

  • catch 문에 error 변수의 타입을 변경할 수 있는 옵션
    • true 인 경우, unknown 타입
    • false 인 경우, any 타입

catch (error: unknown)

  • TypeScript 4.4 에서 error 의 타입을 any에서 unknown으로 변경할 수 있게 됨
  • any 타입일 때보다 더 정확하고 type-safe하게 에러 처리 가능
    • error에 다양한 Error가 들어올 수 있어 any 타입을 사용했지만, unknown 타입이 typescript에 도입된 이후 unknown 타입으로 더 명확하게 에러 처리 가능
  • --useUnknownInCatchVariables을 사용하여 변경 가능
    • true 인 경우, any -> unknown

unknown 타입으로 발생한 에러 및 해결 방법

  • 에러 상황
try {
  // ...
} catch (error) {
  // Object is of type 'unknown'.ts(2571)
  if (error.status === 401) {
      console.log('UnAuthorization');
  }
}
  • 해결 방안
  1. error를 any 타입으로 변경하기
    • tsconfig.json에 useUnknownInCatchVariables 옵션 false로 설정
    • "error: any"로 any 타입 직접 설정
try {
  // ...
} catch (error: any) {
  if (error.status === 401) {
      console.log('UnAuthorization');
  }
}
  1. Type Assertion 으로 error 타입 지정
try {
  // ...
} catch (error) {
  const err = error as CustomError; // type assertion
  if (err.status === 401) {
      console.log('UnAuthorization');
  }
}
  1. Type Gaurd 사용
try {
  // ...
} catch (error) {
  if (error instanceof CustomError) {
    if (error.status === 401) {
      console.log('UnAuthorization');
    }
  }
}

참고
https://devblogs.microsoft.com/typescript/announcing-typescript-4-4/#use-unknown-catch-variables
https://www.typescriptlang.org/tsconfig#useUnknownInCatchVariables

profile
to be frontend engineer

0개의 댓글