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

Ambient Module: `declare module`

~7 min · modules, ambient, declare

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"Ambient 선언이 TypeScript 가 어떻게 거기 가는지 모르고 어딘가에 존재하는 거 묘사."

Ambient 의미

'Ambient' 가 구현 없이 타입 묘사하는 선언에 대한 TypeScript 용어. Compiler 한테 '이 이름이 존재하고 이 타입 가짐; 어떻게 가는지는 날 믿어' 말함. 우리가 cover 한 `.d.ts` 파일이 대부분 ambient 선언으로 구성.

declare module — 3 형태

1. Standalone module 선언: `.d.ts` 의 declare module 'foo' 가 이름으로 import 가능한 module 묘사. 이전 lesson 에서 cover.

2. Wildcard module 선언: declare module '*.css' 가 compiler 한테 `.css` 로 끝나는 어떤 import 든 괜찮고 특정 모양 가진다고 말함. Bundler-based 프로젝트의 CSS-modules 나 asset import 의 흔한 패턴.

3. 기존 module augment: declare module 'react' { interface HTMLAttributes { custom: string } } 가 기존 module 의 interface 에 property 추가. 이게 library 저자가 외부에서 그들의 타입 확장 가능하게 하는 법.

Global augment

`declare global` block 이 global scope augment 가능하게. declare global { interface Window { myApp: ... } } 가 너의 프로젝트 어디서나 `window` 에 property 추가. Interface declaration merging 과 결합, 프로젝트 전반 global 타입 추가되는 법.

Ambient 선언이 어딘가-존재하는-타입에 대한 TypeScript 의 escape hatch. Wildcard, augmentation, global 선언이 TypeScript 의 엄격한 module 모델을 bundler, CSS import, library 확장의 더 느슨한 현실과 다리 놓는 법.

Code

Ambient 선언 — wildcard, augment, global·typescript
// globals.d.ts — bundler-aware import 용 wildcard module 선언.
declare module '*.css' {
  const content: { [className: string]: string };
  export default content;
}

declare module '*.svg' {
  const url: string;
  export default url;
}

// 이제 이 import 들이 compile:
import styles from './app.module.css';   // styles: { [className: string]: string }
import logo from './logo.svg';            // logo: string

// 기존 library 타입 augment.
declare module 'react' {
  interface CSSProperties {
    '--custom-var'?: string;             // style prop 에 CSS 커스텀 property 허용
  }
}

// Global augment.
declare global {
  interface Window {
    __APP_VERSION__: string;
  }
}

window.__APP_VERSION__;   // ✅ 타입 붙음

External links

Exercise

.png (URL 문자열) 과 .json (object) 의 wildcard 선언 setup. 코드에서 각각 일부 import 하고 타입 작동 확인. 왜 Vite (또는 비슷한 bundler) 가 이미 너 위해 이걸 선언해?
Hint
Modern bundler 가 asset import 의 자기 ambient 선언 ship. Vite 쓰면 node_modules/vite/client.d.ts 봐 — 거기 wildcard module 선언 많이 발견.

Progress

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

댓글 0

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

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