[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,87 +2,209 @@
|
||||
id: wiki-2026-0508-declaration-files
|
||||
title: Declaration Files
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AI-DECLARATION-FILES]
|
||||
aliases: [TypeScript .d.ts, Type Definitions, DefinitelyTyped]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.99
|
||||
tags: [TypeScript, JavaScript, DeclarationFiles, Tooling]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [typescript, types, declaration, dts]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
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.x
|
||||
---
|
||||
|
||||
# [[Declaration-Files|Declaration-Files]] (선언 파일, .d.ts)
|
||||
# Declaration Files
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "자바스크립트라는 원석에 타입이라는 주석을 입히는 투명 필름." 구현(Implementation)은 없이 오직 타입 정보(Signature)만 포함하여, 타입스크립트가 JS 코드를 이해하고 자동 완성을 제공하게 돕는 매뉴얼이다.
|
||||
## 매 한 줄
|
||||
> **"매 .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.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **Extension**: `.d.ts` (d는 declaration의 약자).
|
||||
- **Core Role**:
|
||||
- **Bridge**: 컴파일된 JS 파일 옆에서 해당 코드의 타입을 설명함.
|
||||
- **Library [[Support|Support]]**: 직접 TS로 쓰이지 않은 NPM 패키지들에 타입을 부여함.
|
||||
- **[[Ambient Declarations|Ambient Declarations]]**: `window`나 `process` 같은 전역 객체에 타입을 추가하는 용도.
|
||||
- **Compiler [[Behavior|Behavior]]**: 런타임에는 아무런 영향을 주지 않으며, 오직 '에디터'와 '컴파일 타임'의 안정성만을 위해 존재한다.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- 선언 파일과 실제 JS 코드가 불일치(Out-of-sync)할 때 발생하는 '거짓 안전(False sense of security)'이 가장 위험하다. 이를 방지하기 위해 라이브러리 제작자는 `tsc`를 통해 구현부에서 타입을 자동 추출(emitDeclarationOnly)하는 방식을 지향해야 한다.
|
||||
### 매 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.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- Related: [[DefinitelyTyped|DefinitelyTyped]] , TypeScript-Type-System
|
||||
- Practice: Publishing-Dual-CJS-ESM-Packages
|
||||
### 매 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.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
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`.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(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
|
||||
### 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;
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### 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;
|
||||
}
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### 3. Module augmentation
|
||||
```typescript
|
||||
// types/react-augment.d.ts
|
||||
import 'react';
|
||||
declare module 'react' {
|
||||
interface CSSProperties {
|
||||
'--brand-hue'?: string;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### 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
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### 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;
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### 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 }
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### 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]] · [[Type Systems]]
|
||||
- 변형: [[Ambient Declarations]] · [[Module Augmentation]]
|
||||
- 응용: [[Library Authoring]] · [[Monorepo TypeScript]]
|
||||
- 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 |
|
||||
|
||||
Reference in New Issue
Block a user