try {} catch (error) {
if (error) {
error.message; // Property 'message' does not exist on type '{}'
}
}
// unknown 타입이 if 문을 통과하여 {}타입이 됨
// {} 타입은 속성을 사용할 수 없으므로 구체적으로 타입을 주장해야함
try {} catch (error) {
if (error: Error) { // 타입 주장
error.message; // Property 'message' does not exist on type '{}'
}
}
// 타입 단언한것을 유지(기억)하기 위해 변수 사용
try {} catch (error) {
const err = error as Error; // 타입 주장한것을 변수에 기록
if (err) {
err.message; // Property 'message' does not exist on type '{}'
}
}
// Best
try {} catch (error) {
if (error instanceof Error) {
error.message; // Property 'message' does not exist on type '{}'
}
}