# 타입 어설션

## 설명 <a href="#desc" id="desc"></a>

TypeScript 프로그래밍을 하다 보면 **타입 어설션(단언, Assertion)**&#xC744; 사용해야 할 순간이 오게 됩니다. 타입 어설션은 컴파일러에게 **"이 타입이 특정 타입 임을 단언합니다"**&#xB77C;고 말하는 것과 같습니다.&#x20;

다른 언어의 타입 캐스트(Cast)와 비슷하지만, 특별한 검사나 데이터 재구성을 수행하지 않습니다. 런타임 시, 영향을 미치지 않으며 **오직 컴파일 과정에서만 사용**됩니다. 타입 어설션을 처리하는 방법은 2가지 입니다.&#x20;

1번째 방법은 앵글 브라켓(angle-bracket, `<>`) 문법을 사용하는 것입니다.

```typescript
let assertion:any = "타입 어설션은 '타입을 단언'합니다.";

// 방법 1: assertion 변수의 타입을 string으로 단언 처리
let assertion_count:number = (<string>assertion).length;
```

2번째 방법은 `as` 문법을 사용하는 것입니다.

```typescript
let assertion:any = "타입 어설션은 '타입을 단언'합니다.";

// 방법 2: assertion 변수의 타입을 string으로 단언 처리
let assertion_count:number = (assertion as string).length;
```

{% hint style="warning" %}
**두 방법 모두 결과는 동일**합니다. 하지만 **JSX와 함께 사용하는 경우**에는 **as 문법만 허용**됩니다.
{% endhint %}

## 실습 <a href="#practice" id="practice"></a>

{% embed url="<https://stackblitz.com/edit/ts-type-assertion?embed=1&file=index.ts&hideExplorer=1&hideNavigation=1&view=editor>" %}

## 참고 <a href="#reference" id="reference"></a>

{% embed url="<https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions>" %}
TypeScript - 타입 어설션
{% endembed %}

{% embed url="<https://developer.mozilla.org/en-US/docs/Web/API/Event/Event>" %}
Event 생성자
{% endembed %}

{% embed url="<https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events>" %}
커스텀 이벤트 생성 / 실행
{% endembed %}


---

# 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://yamoo9.gitbook.io/typescript/types/type-assertions.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.
