iBetter Books
수정

Ch 02. 첫 번째 TypeScript 프로젝트 만들기

프로젝트 초기화

빈 디렉토리를 만들고 Node.js 프로젝트를 초기화합니다.

mkdir hello-tscd hello-tsnpm init -y

npm init -ypackage.json을 기본값으로 생성합니다. -y를 빼면 프로젝트 이름, 버전, 설명 등을 하나씩 입력합니다. 빠른 시작에는 -y가 편합니다.

TypeScript를 프로젝트 의존성으로 설치합니다.

npm install -D typescript tsx @types/node
패키지 역할
typescript TypeScript 컴파일러 (tsc)
tsx TypeScript 직접 실행
@types/node Node.js API 타입 정의

tsconfig.json 생성

TypeScript 컴파일러 설정 파일을 생성합니다.

npx tsc --init

이 명령어는 tsconfig.json을 생성하면서 모든 옵션에 주석이 달린 파일을 만들어줍니다. 지금은 기본값으로 두고, 다음 챕터에서 각 옵션을 자세히 살펴봅니다.

첫 번째 TypeScript 파일

// 새 파일: src/index.tsfunction greet(name: string): string {  return `Hello, ${name}!`;}const message = greet("TypeScript");console.log(message);

src 디렉토리를 만들고 index.ts 파일을 저장합니다.

mkdir src

방법 1 — tsc로 컴파일 후 실행

# 컴파일npx tsc src/index.ts --outDir dist# 실행node dist/index.js

tsc에 파일 경로를 직접 지정하면 --outDir만으로는 디렉토리 구조를 잡기 어렵습니다. tsconfig.jsonrootDiroutDir을 함께 설정하면 깔끔한 결과가 나옵니다.

// 수정: tsconfig.json (핵심 옵션만 표시){  "compilerOptions": {    "target": "ES2022",    "module": "commonjs",    "outDir": "./dist",    "rootDir": "./src",    "strict": true  },  "include": ["src"]}
# tsconfig.json 기반으로 전체 빌드npx tsc# dist/index.js 생성 확인ls dist# 실행node dist/index.js# Hello, TypeScript!

방법 2 — tsx로 직접 실행

tsx는 컴파일 단계 없이 TypeScript 파일을 바로 실행합니다.

npx tsx src/index.ts# Hello, TypeScript!

개발 중에는 tsx가 훨씬 편합니다. 빌드 결과물이 필요한 배포 시에만 tsc를 사용합니다.

package.json 스크립트 설정

매번 npx를 붙이는 게 번거롭습니다. package.json에 스크립트를 등록합니다.

// 수정: package.json{  "name": "hello-ts",  "version": "1.0.0",  "scripts": {    "dev": "tsx watch src/index.ts",    "start": "node dist/index.js",    "build": "tsc",    "typecheck": "tsc --noEmit"  },  "devDependencies": {    "@types/node": "^22.0.0",    "tsx": "^4.0.0",    "typescript": "^5.8.0"  }}

이제 다음처럼 실행합니다.

npm run dev       # 개발 모드 (파일 변경 시 자동 재실행)npm run build     # 프로덕션 빌드npm run typecheck # 타입 검사만 (빌드 없음)

감시 모드로 개발하기

tsx watch 모드는 파일이 변경되면 자동으로 재실행합니다.

npm run dev

이 상태에서 src/index.ts를 수정하고 저장하면 터미널에 변경 결과가 즉시 출력됩니다. PART 01의 나머지 챕터도 이 방식으로 진행합니다.

타입 오류 확인

일부러 오류를 만들어봅니다.

// 수정: src/index.tsfunction greet(name: string): string {  return `Hello, ${name}!`;}const message = greet(42);   // 숫자를 전달 — 오류!console.log(message);

저장하면 tsx watch가 다음 오류를 출력합니다.

src/index.ts:5:21 - error TS2345:
Argument of type 'number' is not assignable to parameter of type 'string'.

VS Code에서도 greet(42) 부분에 빨간 밑줄이 생깁니다. 마우스를 올리면 오류 내용이 나타납니다.

오류를 원래대로 되돌립니다.

// 수정: src/index.tsfunction greet(name: string): string {  return `Hello, ${name}!`;}const message = greet("TypeScript");console.log(message);

완성된 프로젝트 구조

hello-ts/
├── node_modules/
├── src/
│   └── index.ts
├── dist/               ← tsc 빌드 결과
│   └── index.js
├── package.json
├── package-lock.json
└── tsconfig.json

첫 번째 TypeScript 프로젝트가 완성됩니다. 다음 챕터에서는 tsconfig.json의 각 옵션을 자세히 살펴봅니다.