TypeScript 시작하기 (23)

funfungun·2025년 1월 23일

TypeScript 시작하기

목록 보기
21/21
post-thumbnail

저번 시간에는 외부 파일 이용시 declare & 이상한 ambient module 에 대해서 알아보았습니다. 이번 시간에는 d.ts 파일에 대해 알아보도록 하겠습니다.


  1. d.ts 파일은 타입 정의 보관용 파일입니다. ts 파일에 타입정의가 너무 길면 d.ts 파일을 만들기도 합니다.
    // test.d.ts
    export type Age = number;
    export interface Person {
      name: string;
    }

  1. tsconfig.json 에 declaration 옵션을 true 로 하면, 모든 타입을 정리해놓은 레퍼런스용으로 d.ts 파일을 사용할 수 있습니다. index.ts 파일을 저장하기만 하면 index.d.ts 파일이 자동 생성됩니다. 이 경우 d.ts 파일은 수정하지 않습니다.
    // tsconfig.json
    {
      "compilerOptions": {
        "target": "es5",
        "module": "CommonJS",
        "strictNullChecks": true,
        "declaration": true
      }
    }
    // index.ts
    let nickname: string = "John Doe";
    type Age = number;
    // index.d.ts
    declare let nickname: string;
    type Age = number;

  1. d.ts 파일은 자동으로 ambient module 이 아닙니다. d.ts 파일은 예외적으로 로컬 모듈입니다. 그런데 export/import 하기 싫다면 typeRoots 옵션을 두면 됩니다. types 폴더를 만들고, 그 안에 d.ts 파일을 넣어줍니다. 다만 이것을 사용할 경우 d.ts 자동생성 기능을 끄는 것이 좋습니다.
    // tsconfig.json
    {
      "compilerOptions": {
        "target": "es5",
        "module": "CommonJS",
        "strictNullChecks": true,
        "declaration": true,
        "typeRoots": ["./types"]
      }
    }
    // "./types/test.d.ts"
    type Age = number;
    // index.ts
    let age: Age = 30;

  1. 외부 라이브러리를 사용할 때, 타입 지정이 안되어있다면 직접 해주어야 하는데 유명한 사이트들에서 다른 사람들이 만들어 놓은 것을 사용하면 됩니다. 참고로 typeRoots 옵션이 있는 경우 node_modules/@types 폴더를 추가해야하며, 아니면 typeRoots 옵션을 제거해야 합니다.

(본 포스팅은 코딩애플(Coding Apple)의 '빠르게 마스터하는 타입스크립트' 강의 내용을 바탕으로 학습하며 정리한 글입니다.)

profile
Commercial Art

0개의 댓글