> For the complete documentation index, see [llms.txt](https://yamoo9.gitbook.io/typescript/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://yamoo9.gitbook.io/typescript/introduction/typescript.md).

# TypeScript를 사용하는 이유

## JavaScript  vs  TypeScript

&#x20;코드 량만 보면 굳이 TypeScript를 써야 할까 싶지만, TypeScript를 사용하면 JavaScript와 달리 코드 작성 과정에서 코드를 실시간으로 디버깅할 수 있어 매우 편리합니다. JavaScript와 TypeScript 사용 예를 비교해봅니다.

### JavaScript

작성된 함수 코드를 보면 아래 TypeScript 코드보다 간결해보입니다. 하지만 함수 실행 과정에서 전달해야 할 각 인자의 타입을 안내받지 못할 경우 의도치 않은 문제가 발생할 소지가 있습니다.

```javascript
function ellipsisText(text, limit, symbol='...') {
  return `${String(text).slice(0, limit - 1)}${symbol}`
}
```

아래 함수 실행 예시 코드를 보면 문제가 발생했음에도 오류를 표시하지 않습니다.

```javascript
ellipsisText(100304040202, 30, 101) // 결과 값: "100304040202101"
```

### JavaScript + 유효성 검사

오류를 안내하지 않는 함수는 여러 문제를 야기할 수 있으므로 함수 선언 시 다음과 같이 각 매개변수로 전달 받을 값의 유형을 검사해 문제를 해결할 수 있지만 이와 같은 검사 과정을 직접 작성하는 것은 매우 번거롭고 불편합니다.

```javascript
function ellipsisText(text, limit, sybol='...') {
  if (typeof text !== 'string') throw new Error('1번째 전달인자 유형은 문자여야 함')
  if (typeof limit !== 'number') throw new Error('2번째 전달인자 유형은 숫자여야 함')
  if (typeof symbol !== 'string') throw new Error('3번째 전달인자 유형은 문자여야 함')
  return `${text.slice(0, limit - 1)}${symbol}`
}
```

아래 함수 실행 예시 코드는 앞서와 달리 문제가 발생되었음을 오류로 표시합니다.

```javascript
ellipsisText(100304040202, 30, 101)
```

{% hint style="danger" %}
**Uncaught Error: 1번째 전달인자 유형은 문자여야 함**
{% endhint %}

### TypeScript (비교)

TypeScript로 작성된 코드는 앞서 작성한 JavaScript 함수 코드보다 다소 복잡해보이지만, 작성 후 함수 실행 시, 컴파일 과정에서 실시간으로 타입을 검사하므로 디버깅이 쉽고 안정된 프로그램 작성을 가능하게 합니다.

```typescript
function ellipsisText(text:string, limit:number, symbol:string = '...'):string {
  return `${text.slice(0, limit - 1)}${symbol}`
}
```

TypeScript를 사용한 선언 과정에서 설정된 타입에 의해 컴파일 과정에서 실시간으로 오류를 표시합니다.

```typescript
ellipsisText(10203010201, 30)
```

{% hint style="danger" %}
**Argument of type 'number' is not assignable to parameter of type 'string'.**
{% endhint %}

### 직접 실습해볼까요?

TypeScript를 직접 입력한 후, [**실시간으로 컴파일 디버깅되는 과정**](https://bit.ly/3mRPdae)을 확인하세요.

![](https://607986862-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LDS-orWYJdO9Wve6CUx%2F-MNwPF6_lEb2ocfHewQd%2F-MNwPhRA9_P7g1MJRxFF%2Fimage.png?alt=media\&token=a1c56e0c-0cea-432e-9011-b61dc4ddd45f)
