Files
2nd/10_Wiki/Topics/Architecture/Ambient_Declarations.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.8 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-ambient-declarations Ambient Declarations 10_Wiki/Topics verified self
.d.ts
declare keyword
TypeScript ambient
Type definitions
none A 0.9 applied
typescript
types
declarations
dts
interop
2026-05-10 pending
language framework
typescript TypeScript 5.7

Ambient Declarations

매 한 줄

"매 type-only declarations — 매 describe shapes that exist elsewhere". 매 TypeScript (Anders Hejlsberg, 2012) 매 since v0.8 매 .d.ts files. 매 DefinitelyTyped (2014) → @types/* npm scope (2016) → TS 4.x package "exports" + types (2021) → TS 5.7 (2026 stable) 매 --isolatedDeclarations 매 fast .d.ts emit.

매 핵심

매 ambient 의 의미

  • Ambient: 매 declaration only, 매 no implementation. 매 emit 매 not 매 produce JS.
  • .d.ts files: 매 declarations only. 매 imports 매 type-erased.
  • declare keyword: 매 inside .ts files 매 declare 매 ambient binding.

매 use cases

  • Type 3rd-party JS library (no built-in types).
  • Type global runtime (browser, Node, custom).
  • Augment existing module/global.
  • Distribute types separate from JS (npm "types" field).
  • Emit minimal API surface from TS source.

매 응용

  1. @types/ packages* — DefinitelyTyped community types.
  2. Global augmentation — extend Window, process.env.
  3. Module augmentation — add methods to existing module's interface.
  4. Asset typing*.svg *.css import as module.

💻 패턴

Basic ambient module (3rd-party JS)

// types/legacy-lib.d.ts
declare module "legacy-lib" {
  export function greet(name: string): string;
  export interface Config { timeout: number }
  export default class Client {
    constructor(cfg: Config);
    send(msg: string): Promise<void>;
  }
}

Ambient global

// types/globals.d.ts
declare global {
  var __APP_VERSION__: string;
  interface Window {
    analytics?: { track(event: string, props?: object): void };
  }
  namespace NodeJS {
    interface ProcessEnv {
      DATABASE_URL: string;
      REDIS_URL: string;
    }
  }
}
export {};  // 매 file 의 module 의 만듦 — augmentation 매 valid

Module augmentation (extend existing)

// add-toJSON.d.ts
import "express";
declare module "express" {
  interface Request {
    user?: { id: string; role: "admin" | "user" };
    requestId: string;
  }
}
// Now in any file: req.user is typed

Asset module typing

// assets.d.ts
declare module "*.svg" {
  const url: string;
  export default url;
}
declare module "*.css" {
  const classes: { readonly [key: string]: string };
  export default classes;
}
declare module "*.json" {
  const value: unknown;
  export default value;
}

Triple-slash directive (legacy, still used)

/// <reference types="node" />
/// <reference path="./vendor.d.ts" />

declare inside .ts file

// app.ts
declare const FEATURE_FLAGS: { newCheckout: boolean };
declare function gtag(cmd: string, ...args: unknown[]): void;

if (FEATURE_FLAGS.newCheckout) gtag("event", "view_new_checkout");

Conditional types via ambient

// react-augmentation.d.ts
import "react";
declare module "react" {
  interface CSSProperties {
    "--theme-color"?: string;
    "--theme-radius"?: string;
  }
}
// Now: <div style={{ "--theme-color": "blue" }}/> typechecks

tsconfig declarations

{
  "compilerOptions": {
    "declaration": true,
    "declarationMap": true,
    "emitDeclarationOnly": false,
    "isolatedDeclarations": true,
    "types": ["node", "vitest/globals"],
    "typeRoots": ["./node_modules/@types", "./types"]
  }
}

Library author (publish .d.ts)

// package.json
{
  "name": "my-lib",
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.mjs",
      "require": "./dist/index.cjs"
    }
  }
}

매 결정 기준

상황 Approach
3rd-party JS lib, no types Check @types/lib first; else write .d.ts
Add field to req/res in Express/Fastify Module augmentation
Type custom Vite/Webpack asset import Wildcard module decl
Globals (browser/Node) declare global { ... } + export {}
Library publish TS source → emit .d.ts (declaration: true)

기본값: 매 prefer @types/* package, 매 fall back 매 hand-written .d.ts, 매 augmentation 매 last resort (subtle to debug).

🔗 Graph

🤖 LLM 활용

언제: 매 untyped JS interop, 매 global runtime typing, 매 library distribution, 매 framework extension points. 언제 X: 매 internal TS code (use regular interface/type), 매 enforcement need (declarations 매 erased — runtime check 매 separate).

안티패턴

  • any everywhere in .d.ts: 매 type loss 의 propagation. 매 unknown + narrow.
  • Augmenting without export {}: 매 file 매 script 의 treated, 매 augmentation silently fails.
  • Triple-slash in modern code: 매 prefer tsconfig "types" array.
  • Global pollution: 매 every helper 매 global 의 declare → namespace clashes.

🧪 검증 / 중복

  • Verified (TypeScript Handbook "Declaration Files", DefinitelyTyped contribution guide, TS 5.7 release notes).
  • 신뢰도 A.

🕓 Changelog

날짜 변경
2026-05-08 Phase 1
2026-05-10 Manual cleanup — full content (.d.ts, declare, augmentation patterns)