Files
2nd/10_Wiki/Topics/Frontend/Declaration-Files.md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

5.6 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-declaration-files Declaration Files 10_Wiki/Topics verified self
TypeScript .d.ts
Type Definitions
DefinitelyTyped
none A 0.9 applied
typescript
types
declaration
dts
2026-05-10 pending
language framework
TypeScript 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.tsdeclare 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

// 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)

// 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

// types/react-augment.d.ts
import 'react';
declare module 'react' {
  interface CSSProperties {
    '--brand-hue'?: string;
  }
}

4. Global augmentation

// 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

// 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

// 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)

{
  "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

{
  "compilerOptions": {
    "declaration": true,
    "declarationMap": true,
    "emitDeclarationOnly": false,
    "outDir": "dist",
    "rootDir": "src",
    "moduleResolution": "bundler"
  }
}

9. tsup d.ts bundle

// 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

// 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

🤖 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