[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,104 +2,202 @@
|
||||
id: wiki-2026-0508-ambient-declarations
|
||||
title: Ambient Declarations
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [.d.ts, declare keyword, TypeScript ambient, Type definitions]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [auto-consolidated, technical-documentation]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [typescript, types, declarations, dts, interop]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-08
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: typescript
|
||||
framework: TypeScript 5.7
|
||||
---
|
||||
|
||||
# [[Ambient Declarations|Ambient Declarations]]
|
||||
# Ambient Declarations
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> 핵심 요약 작업 진행 중
|
||||
## 매 한 줄
|
||||
> **"매 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.
|
||||
|
||||
---
|
||||
## 매 핵심
|
||||
|
||||
> "존재하지만 실체는 없는 것들에 대한 증명." 타입스크립트 컴파일러에게 "이 변수나 함수는 외부에 이미 있으니 타입만 믿고 통과시켜라"라고 알려주는 `declare` 키워드의 본질이다.
|
||||
### 매 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.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
본문 상세 구성 진행 중
|
||||
### 매 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.
|
||||
|
||||
- **declare keyword**:
|
||||
- 실제 컴파일된 JS 파일에는 포함되지 않지만, 타입 전용 공간에서 전역 변수나 라이브러리의 구조를 선언할 때 사용한다.
|
||||
- **.d.ts files**:
|
||||
- 앰비언트 선언들이 모여 있는 파일. 프로젝트 전체에 걸쳐 전역적인 타입 정보를 제공하는 '타입 명세서' 역할을 한다.
|
||||
- **External Library Integration**:
|
||||
- 타입 정보가 없는 레거시 JS 라이브러리를 타입스크립트 프로젝트에서 에러 없이 사용하기 위한 필수 관문이다.
|
||||
## 💻 패턴
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 지식 자산화 및 기존 네트워크 연동 단계.
|
||||
- **정책 변화:** Programming & Language 카테고리의 전문성 확보 및 링크 밀도 최적화.
|
||||
|
||||
---
|
||||
|
||||
- 무분별한 앰비언트 선언은 전역 네임스페이스를 오염시킨다. 현대적 가이드라인은 가능하면 `Module Augmentation`을 사용하거나 `@types` 패키지를 통해 엄격하게 관리하는 것을 권장한다.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
- Related: [[Declaration-Files|Declaration-Files]] , Module-Augmentation
|
||||
- Standard: [[Branded-Types-for-Nominal-Typing|Branded-Types-for-Nominal-Typing]]
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### Basic ambient module (3rd-party JS)
|
||||
```typescript
|
||||
// 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>;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Ambient global
|
||||
```typescript
|
||||
// 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
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Module augmentation (extend existing)
|
||||
```typescript
|
||||
// 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
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Asset module typing
|
||||
```typescript
|
||||
// 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;
|
||||
}
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Triple-slash directive (legacy, still used)
|
||||
```typescript
|
||||
/// <reference types="node" />
|
||||
/// <reference path="./vendor.d.ts" />
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### `declare` inside .ts file
|
||||
```typescript
|
||||
// app.ts
|
||||
declare const FEATURE_FLAGS: { newCheckout: boolean };
|
||||
declare function gtag(cmd: string, ...args: unknown[]): void;
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
if (FEATURE_FLAGS.newCheckout) gtag("event", "view_new_checkout");
|
||||
```
|
||||
|
||||
### Conditional types via ambient
|
||||
```typescript
|
||||
// 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
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"emitDeclarationOnly": false,
|
||||
"isolatedDeclarations": true,
|
||||
"types": ["node", "vitest/globals"],
|
||||
"typeRoots": ["./node_modules/@types", "./types"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Library author (publish .d.ts)
|
||||
```json
|
||||
// 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
|
||||
- 부모: [[TypeScript]] · [[Type System]]
|
||||
- 변형: [[Module Augmentation]] · [[Global Augmentation]] · [[Triple-slash Directives]]
|
||||
- 응용: [[DefinitelyTyped]] · [[Library Publishing]] · [[Asset Typing]]
|
||||
- Adjacent: [[tsconfig.json]] · [[Type Inference]] · [[Conditional Types]]
|
||||
|
||||
## 🤖 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) |
|
||||
|
||||
Reference in New Issue
Block a user