---
id: wiki-2026-0508-declaration-files
title: Declaration Files
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [TypeScript .d.ts, Type Definitions, DefinitelyTyped]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [typescript, types, declaration, dts]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: TypeScript
  framework: TypeScript 5.x
---

# Declaration Files

## 매 한 줄
> **"매 .d.ts = type-only public surface — runtime code 의 X."**. 매 TypeScript의 매 declaration 파일이 매 JS library의 매 type contract 의 제공 — `@types/node`, `@types/react` 등 매 DefinitelyTyped 가 매 ecosystem 의 backbone. 매 modern (2024-2026) 워크플로우는 `tsc --declaration` 자동 생성 + `tsup` / `rollup-plugin-dts` 의 bundling.

## 매 핵심

### 매 file types
- `lib.d.ts` — TS standard library (DOM, ES2024).
- `package.d.ts` — package 자체 type.
- `globals.d.ts` — ambient declaration (window 확장).
- `module.d.ts` — `declare module 'foo'` shape.

### 매 publishing
- `package.json` `"types"` (or `"typings"`) field → main d.ts entry.
- `"exports"` map (Node 16+) — multiple entry points + types.
- Dual ESM/CJS = 매 두 d.ts 필요 — `"types"` per condition.

### 매 응용
1. JS library 의 type 추가 — `@types/foo`.
2. Module augmentation — `declare module 'react' { ... }`.
3. CSS modules / image import — `*.module.css` declaration.
4. Env variable typing — `import.meta.env`.

## 💻 패턴

### 1. Basic .d.ts
```typescript
// lib.d.ts
export interface User { id: string; name: string }
export declare function getUser(id: string): Promise<User>;
export declare const VERSION: string;
```

### 2. Module declaration (ambient)
```typescript
// types/legacy-lib.d.ts
declare module 'legacy-lib' {
  export function init(opts: { key: string }): void;
  const version: string;
  export default version;
}
```

### 3. Module augmentation
```typescript
// types/react-augment.d.ts
import 'react';
declare module 'react' {
  interface CSSProperties {
    '--brand-hue'?: string;
  }
}
```

### 4. Global augmentation
```typescript
// types/globals.d.ts
declare global {
  interface Window {
    analytics?: { track(event: string, props?: Record<string, unknown>): void };
  }
}
export {}; // make this a module
```

### 5. Asset module declarations
```typescript
// types/assets.d.ts
declare module '*.module.css' {
  const classes: Record<string, string>;
  export default classes;
}
declare module '*.svg' {
  const url: string;
  export default url;
}
declare module '*.svg?react' {
  import { FC, SVGProps } from 'react';
  const Component: FC<SVGProps<SVGSVGElement>>;
  export default Component;
}
```

### 6. Vite env types
```typescript
// src/vite-env.d.ts
/// <reference types="vite/client" />
interface ImportMetaEnv {
  readonly VITE_API_URL: string;
  readonly VITE_SENTRY_DSN: string;
}
interface ImportMeta { readonly env: ImportMetaEnv }
```

### 7. package.json exports + types (dual ESM/CJS)
```json
{
  "name": "@acme/lib",
  "type": "module",
  "main": "./dist/index.cjs",
  "module": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js",
      "require": "./dist/index.cjs"
    },
    "./feature": {
      "types": "./dist/feature.d.ts",
      "import": "./dist/feature.js"
    }
  }
}
```

### 8. tsconfig for d.ts emit
```json
{
  "compilerOptions": {
    "declaration": true,
    "declarationMap": true,
    "emitDeclarationOnly": false,
    "outDir": "dist",
    "rootDir": "src",
    "moduleResolution": "bundler"
  }
}
```

### 9. tsup d.ts bundle
```javascript
// tsup.config.ts
import { defineConfig } from 'tsup';
export default defineConfig({
  entry: ['src/index.ts'],
  format: ['esm', 'cjs'],
  dts: true,           // bundle d.ts
  sourcemap: true,
  clean: true,
});
```

### 10. Conditional type for string literal API
```typescript
// route.d.ts — type-safe routing
type Route =
  | { name: 'home'; params?: undefined }
  | { name: 'user'; params: { id: string } };

declare function navigate<R extends Route>(...args: R['params'] extends undefined ? [name: R['name']] : [name: R['name'], params: R['params']]): void;
```

## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 JS library 의 type | `@types/foo` (DefinitelyTyped). |
| 매 own library | `tsc --declaration` or tsup `dts: true`. |
| 매 monorepo internal | `composite: true` + project references. |
| 매 CSS / asset import | `*.module.css` ambient declaration. |
| Plugin-based extension | Module augmentation. |

**기본값**: tsup `dts: true` + `exports` map + declarationMap.

## 🔗 Graph
- 부모: [[TypeScript]] · [[TypeScript 타입 시스템 (TypeScript Type System)|Type Systems]]
- 변형: [[Ambient Declarations]]
- Adjacent: [[DefinitelyTyped]] · [[tsup]] · [[Vite]]

## 🤖 LLM 활용
**언제**: 매 d.ts scaffolding, ambient module declaration, exports map.
**언제 X**: 매 complex generic inference debug — 매 TS playground 사용.

## ❌ 안티패턴
- **No `export {}` in global aug**: 매 file 이 script 로 처리됨 → 매 declare global 무효.
- **`any` everywhere**: 매 d.ts 의 가치 의 negate.
- **`types` 미게시**: 매 user 의 `@types/foo` 의 별도 작성 필요.
- **Conditional exports types last**: 매 `"types"` 가 매 conditions 의 first 위치 — 매 spec.

## 🧪 검증 / 중복
- Verified (typescriptlang.org/docs/handbook/declaration-files, TS 5.x release notes).
- 신뢰도 A.

## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — d.ts authoring + exports map 2026 |
