HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🚀
개발 노트
/
🥈
타입스크립트 error와 instanceof
🥈

타입스크립트 error와 instanceof

 
TypeScript는 error의 기본 타입을 unknown으로 갖는다. 던져진 에러의 타입에 대해서는 확신이 부족하다. 실제로 던져진 값은 에러가 아닐 수도 있기 때문이다. 아래와 같은 어떤 값도 가능하다.
throw "What the!?"; throw 7; throw { wut: "is this" }; throw null; throw new Promise(() => {}); throw undefined;
 
아래와 같이 에러를 핸들링할 수 있다.
 
try { throw new Error("Oh no!"); } catch (error) { let message; if (error instanceof Error) message = error.message; else message= String(error); // 진행은 하겠지만, 리포트는 전송하자.reportError({ message }); }
 

instanceof

instanceof 연산자로 객체가 특정 생성자(또는 클래스)에 속하는지 아닌지를 확인할 수 있다. 상속 관계도 확인해준다.
 
object instanceof constructor object instanceof class
 
object의 프로토타입 체인에 constructor.prototype이 존재한다면 true,
그렇지 않으면 false를 반환한다.
 
 
notion image
 
 
Get a catch block error message with TypeScript
Alrighty, let's talk about this: Good so far? Well, that's because this is JavaScript. Let's throw TypeScript at this: That reportError call there isn't happy. Specifically it's the error.message bit. It's because (as of recently) TypeScript defaults our error type to unknown. Which is truly what it is!
Get a catch block error message with TypeScript
https://kentcdodds.com/blog/get-a-catch-block-error-message-with-typescript
Get a catch block error message with TypeScript
'instanceof'로 클래스 확인하기
instanceof 연산자를 사용하면 객체가 특정 클래스에 속하는지 아닌지를 확인할 수 있습니다. instanceof 는 상속 관계도 확인해줍니다. 확인 기능은 다양한 곳에서 쓰이는데, 이번 챕터에선 instanceof를 사용해 인수의 타입에 따라 이를 다르게 처리하는 다형적인(polymorphic) 함수를 만드는데 사용해보겠습니다. 문법은 아래와 같습니다. obj가 Class에 속하거나 Class를 상속받는 클래스에 속하면 true 가 반환됩니다.
'instanceof'로 클래스 확인하기
https://ko.javascript.info/instanceof
'instanceof'로 클래스 확인하기
instanceof - JavaScript | MDN
다른 스코프는 다른 실행 환경을 가집니다. 이것은 다른 스코프는 다른 고정된 요소들(다른 전역 오브젝트, 다른 생성자들 등)을 가지고 있음을 의미합니다. 이 사실은 예상치 못한 결과를 가져올 수도 있습니다. 예를 들면, [] instanceof window.frames[0].Array는 false를 리턴할 것입니다. 왜냐하면, Array.prototype !== ``window.frames[0].Array 이며, arrays 는 상위로부터 상속받기 때문입니다. 이것은 처음에는 말이 되지 않을 수도 있습니다.
instanceof - JavaScript | MDN
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/instanceof
instanceof - JavaScript | MDN