# 타입스크립트 건망증

## 타입스크립트도 떠먹여줘야한다.&#x20;

```typescript
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 '{}'
  }
}
```

* error는 unknown 타입
* as로 강제 **단언한것은 일시적임**
  * 판단한 문장에만 허용되므로 **단언한 타입을 계속 기억할 수 있게 만들어야 한다.**
  * -> **변수에 담아야 오래 기억한다.**
* as를 사용하지 않고 깔끔하게 타입 추론이 되는 방법이 있다면 그 방법을 사용

{% hint style="warning" %}
**`unknown`**&#xC740; if문을 통과하면 `{}`타입이 된다.

**`{}`** 타입은 속성을 사용할 수 없는 타입
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://taewoongs-organization.gitbook.io/jtwjs-dev-wiki/dev_note/typescript/undefined/undefined-7.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
