TypeScript compiler and tsc

hyeyeong lee·2023년 7월 26일

Compiler

- 특정 programming 언어가 정적 언어(Compiled Language)로서의 정체성을 유지할 수 있게 하는 도구
- programming 언어로 작성된 source code를 다른 programming 언어로 변환

역할

  • tsc (TypeScript Compiler): TypeScript를 JavaScript code로 변환
  • source code의 정적 type 검사를 수행하여 type 관련 오류를 미리 발견하고 수정

특징

  • 변환 과정에서 compiler가 source code의 구문과 구조 검사
  • source code에서 문제가 발견되면 error message 출력
  • code가 최적화되면 전반적인 application 실행 시간 단축


tsconfig.json의 필수 옵션(compilerOptions)

option menual

strict : 엄격한 type 검사 option을 모두 활성화
└[참고] code에서 강하게 type을 정의할 수 있고, type 정의에 대한 오류를 대응할 수 있어 안전하게 coding을 할 수 있게 한다.
target : 어떤 JavaScript version으로 변환할지 선택
module : TypeScript file을 compile한 후 생성되는 JavaScript module의 형식 지정
outDir : compile된 JavaScript file이 저장될 출력 directory 지정
sourceMap : JavaScript file에 대한 sourceMap을 생성하여 실행 중에 error가 발생했을 때 원래 TypeScript source code의 위치 확인 가능
include : src directory 밑의 file들을 compile 하겠다는 의미
exclude : node_modules, dist directory 밑의 file들을 compile 대상에서 제외하겠다는 의미




.d.ts file

- JavaScript library도 TypeScript code에서 사용할 수 있게 해주는 도구
- 이미 작성된 다양한 JavaScript library와 호환성 유지

역할

  • .d.ts file은 TypeScript type 정의 file
  • JavaScript library에 대한 type 정보 제공 (외부 library의 함수, class, 객체 type 정보)


사용 방법

  1. Node.js 프로젝트 생성
    npm init -y
  1. tsconfig.json을 생성하여 TypeScript project로 변환
    tsc --init --rootDir ./src --outDir ./dist --esModuleInterop --module commonjs --strict true --allowJS true --checkJS true
  1. TypeScript에서 사용하고 싶은 custom JavaScript library를 생성
    /
    * @param {number} a
    * @param {number} b
    * @returns {number}
    */
    export function add(a, b) {
      return a + b;
    }
    1) 위의 주석문은 'JSDoc'로 API의 signature(인자, return type)를 설명하는 HTML 문서 생성기
    3) JSDoc으로 JavaScript source code에 type hint 제공 가능
  1. type hint가 제공된 test.js의 .d.ts 파일 생성
    npx tsc test.js --declaration --allowJs --emitDeclarationOnly --outDir types
  1. types/test.d.ts 파일을 확인하면 다음과 같이 생성됨
    /
    * @param {number} a
    * @param {number} b
    * @returns {number}
    */
    export function add(a: number, b: number): number;
  1. test.js 파일을 참조할 foo.ts 파일을 새로 생성
    import { add } from "./test";
    console.log(add(1, 2));
  1. 다음의 명령어를 실행하여 3이라는 숫자가 뜨면 정상적으로 실행
    npx ts-node foo.ts

0개의 댓글