2023. 4. 18. 15:28ㆍJavaScript/Typescript
| 목차 |
| 1. 타입스크립트(Typescript) |
| 2. 타입스크립트의 장, 단점 |
| 3. 타입스크립트의 런타임 |
| 4. 타입스크립트 컴파일러 |
1. 타입스크립트(Typescript)
타입스크립트는 MS에서 개발한 오픈소스 프로그래밍 언어이며,
자바스크립트의 상위 집합 언어이다.

자바스크립트는 런타임 시점에 변수의 타입이 결정되는 동적 타입 언어이다.
이는 런타임시 에러가 발생할 수 있는데 코드를 작성할 때에는 이를 알 수가 없다.
반면에 타입스크립트는 변수의 타입을 미리 명시하고, 컴파일 시간에 타입 검사를 수행한다.
타입스크립트는 이런 정적 타입 언어의 특성을 가져 파일을 실행하기 전에 어디서 에러가 발생할지 미리 알 수 있다.
2. 타입스크립트(Typescript)의 장,단점
장점
- 동적언어인 자바스크립트를 런타임 전에 어느정도 오류를 잡을 수 있다.
단점
- 타입스크립트는 자바스크립트에서 굳이 치지 않아도 되었던 코드를 치게되어 코드량이 많아진다.
- 런타임이 존재하지 않아, 빌드하는 과정이 반드시 필요하다(타입스크립트 컴파일러가 존재한다.)
3. 타입스크립트의 런타임
message.ts라는 파일을 한번 작성하고 node로 실행을 해보도록하자.
const message: string = "hello world"
console.log(message)
// /home/char1ey/workspace/blockchain/230418/1.runtime/message.ts:1
// const message: string = "typescript"
// ^^^^^^^
// SyntaxError: Missing initializer in const declaration
// at Object.compileFunction (node:vm:360:18)
// at wrapSafe (node:internal/modules/cjs/loader:1088:15)
// at Module._compile (node:internal/modules/cjs/loader:1123:27)
// at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
// at Module.load (node:internal/modules/cjs/loader:1037:32)
// at Module._load (node:internal/modules/cjs/loader:878:12)
// at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
// at node:internal/main/run_main_module:23:47
// Node.js v18.12.1
node message.ts
node로 위의 파일을 실행시켰으나, ts파일을 읽을 수 없어 에러를 출력한다.
즉, 런타임이 없는 타입스크립트 파일을 실행시키는 법을 알아야한다.
4. 타입스크립트 컴파일러
타입스크립트를 실행하기 위한 몇 가지 방법이 존재한다.
- 타입스크립트 컴파일러 설치
- 바벨을 통해서 플러그인에 타입스크립트 관련된 것을 설정한 뒤 실행
- 웹팩을 통해서 바벨, 플러그인 등을 설정하여 번들링해서 js로 변환하여 실행
결국 타입스크립트의 컴파일 과정이 필요하다.
타입스크립트를 실행 시키기 위해서는 컴파일이 필요하다.
타입스크립트의 컴파일러를 설치해보도록 하자.
$ npm init -y
$ npm install -D typescript
# 혹은
$ npm install -g typescript
컴파일러를 받았다면, tsc 명령어를 사용할 수 있게된다.
$ tsc [파일위치/파일명]
3번에서 만들어 놓은 message.ts를 컴파일 해보도록 하자
$ tsc message.ts
같은 디렉토리에 아래의 내용으로 바뀐 message.js가 생성이 된다.
const message = "hello world";
console.log(message); // hello world
생성된 파일은 기존의 자바스크립트 파일과 같기 때문에 node 환경에서도 실행을 할 수 있게 된다.
'JavaScript > Typescript' 카테고리의 다른 글
| 전략패턴 실습코드(230420) (0) | 2023.04.23 |
|---|---|
| 타입스크립트 문법(2) (0) | 2023.04.20 |
| 타입스크립트 문법(1) (0) | 2023.04.19 |
| 타입스크립트 실습코드(OOP) (230419) (0) | 2023.04.19 |
| 타입스크립트 기본설정하기 (0) | 2023.04.18 |