C.W.K.
Stream
Lesson 03 of 05 · published

`.d.ts`: TypeScript 한테 JavaScript 에 대해 말하기

~9 min · modules, d-ts, declaration-files

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"Declaration 파일이 구현 없이 모양 묘사. TypeScript 가 타입 안 붙은 JavaScript 타입 붙이는 법."

`.d.ts` 파일이 뭐

`.d.ts` 파일이 타입 정보만 담음 — 변수, 함수, class, module 의 선언. 함수 body 없음, class body 없음, 값 없음. Compiler 가 읽어서 JavaScript module 이 어떤 타입 export 하는지 이해.

npm 의 대부분 library 가 자기 `.d.ts` 파일을 `.js` 와 함께 ship. 안 하면 community-maintained `@types/library-name` 패키지가 보통 제공. TypeScript compiler 가 자동으로 둘 다 찾음.

자기 거 쓰기

타입 안 붙은 JavaScript library 쓸 때, `.d.ts` 파일 써서 TypeScript 한테 뭐 export 하는지 말할 수. `tsconfig.json` 의 `include` 가 cover 하는 어디든 둬 — 보통 프로젝트 root 또는 `types/` 디렉토리.

// custom-lib.d.ts
declare module 'custom-lib' {
  export function doThing(x: number): string;
  export interface Config { host: string }
}

이제 import { doThing } from 'custom-lib' 가 library 가 embedded 타입 없어도 적절한 타입과 함께 컴파일.

TypeScript standard library

Array, Map, Set, Promise, fetch, document 등의 타입이 다 `node_modules/typescript/lib/` 안의 `.d.ts` 파일에 살아. ES5 엔 `lib.es5.d.ts`; 브라우저엔 `lib.dom.d.ts`; 더 새 ES 기능엔 `lib.es2022.d.ts`. Tsconfig `lib` 옵션이 어느 게 load 될지 제어.

`.d.ts` 파일이 TypeScript 가 JavaScript 다시 쓰게 강제 안 하면서 JavaScript 와 interoperable 하게 유지하는 법. 어떤 module 이든 — 타입 붙었든 안 붙었든 — declaration 파일 써서 타입 줄 수.

Code

타입 안 붙은 module 의 .d.ts 쓰기·typescript
// my-lib.d.ts — 타입 안 붙은 module 선언.
declare module 'untyped-lib' {
  export function add(a: number, b: number): number;
  export const VERSION: string;
  export default class Thing {
    constructor(name: string);
    getName(): string;
  }
}

// consumer.ts — 이제 타입 붙은 module 사용.
import Thing, { add, VERSION } from 'untyped-lib';

add(1, 2);            // ✅ 타입 붙음
Thing;                // ✅ class
VERSION;              // ✅ string

// Declaration 파일이 global 도 선언 가능.
declare global {
  interface Window {
    appConfig: { apiBase: string };
  }
}
window.appConfig.apiBase;   // ✅ — 이제 어디서나 타입 붙음

External links

Exercise

타입 없는 작은 JavaScript library 찾아 (또는 상상). 그것에 함수 2개와 상수 1개 선언하는 .d.ts 써. TypeScript 코드에서 import 하고 autocomplete 작동 확인.
Hint
declare module 'name' block 이 TypeScript 한테 '이 module 가 이 export 가짐' 말함. 함수 body 없이 — signature 만.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.