@moon791017/neo-skills 1.0.41 → 1.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -1,9 +1,6 @@
1
1
  # Neo Skills Extension (agents.md)
2
2
 
3
- **Neo Skills** 是一個專為 **Antigravity CLI (AGY)** 設計的擴充外掛,旨在將 Agent 轉化為**全方位專家代理 (Universal Expert Agent)**。它利用 Model Context Protocol (MCP) 提供特定領域的專業知識 (Skills)。目前配備了專業的 **DevOps** 模組(Azure Pipelines),其架構設計可託管任何領域的技能。
4
-
5
- ## 核心約束
6
- - 所有 MCP 指令必須由使用者手動執行,不可自動化!
3
+ **Neo Skills** 是一個專為 **Antigravity CLI (AGY)** 設計的擴充外掛,旨在將 Agent 轉化為**全方位專家代理 (Universal Expert Agent)**。它利用 Model Context Protocol (MCP) 提供特定領域的專業知識 (Skills)。目前配備了專業的 **DevOps**(Azure Pipelines)與 **Frontend/Backend** 多語系(.NET, Python, Swift, TypeScript/JavaScript, Rust, Vue)等領域的模組,其架構設計可託管任何領域的技能。
7
4
 
8
5
  ## 回應風格
9
6
  使用「繁體中文 (台灣)」
@@ -49,7 +46,7 @@ Do not commit secrets, sample credentials, or unsafe prompts. If you change secr
49
46
  * **載入邏輯:**
50
47
  * **全域技能**: 載入自 `~/.gemini/antigravity-cli/plugins/`。
51
48
  * **專案專屬技能**: 載入自專案根目錄下的 `.agents/skills/`(遷移自舊有的 `.gemini/skills/`)。
52
- * **範例:** `skills/neo-azure-pipelines/` 包含設計 CI/CD 管線的邏輯。
49
+ * **範例:** `skills/neo-azure-pipelines/` 包含設計 CI/CD 管線的邏輯,`skills/neo-typescript/` 包含 TypeScript 強型別與互通性最佳實踐。
53
50
 
54
51
  ### 3. 安全層 (`src/hooks/`)
55
52
  確保操作安全與數據隱私的機制。
package/README.md CHANGED
@@ -34,11 +34,11 @@
34
34
 
35
35
  * **智能審查**:針對程式碼變更進行多面向 (正確性、安全性、效能、可讀性) 的深度審查。
36
36
 
37
- ### 4. 程式碼解釋助手
37
+ ### 3. 程式碼解釋助手
38
38
 
39
39
  * **技術解析**:深入分析原始碼或專案結構,提供高階用途摘要、邏輯流程分解以及核心元件說明。
40
40
 
41
- ### 5. .NET / C# 開發專家
41
+ ### 4. .NET / C# 開發專家
42
42
 
43
43
  * **C# 現代語法專家 (`skills/neo-csharp`)**:跨版本 C# 專家 (10-14+),專注於現代化語法、強型別與高效能開發模式。
44
44
  * **.NET 核心路由 (`skills/neo-dotnet`)**:環境偵測與統一入口,自動將任務委派給最合適的子領域專家。
@@ -49,20 +49,27 @@
49
49
  * **.NET Tag Helper 專家 (`skills/neo-dotnet-tag-helper`)**:開發 ASP.NET Core 自定義 Tag Helper 的專家指引,專注於純 C# 實作與異步渲染最佳實踐。
50
50
  * **Interface 生成器**:針對 C# Class 自動生成符合規範的 Interface,並支援智慧檔案覆蓋功能。
51
51
 
52
- ### 6. Python 開發與環境管理專家
52
+ ### 5. Python 開發與環境管理專家
53
53
 
54
54
  * **Python 3.10+ 專家 (`skills/neo-python`)**:專注於 Python 3.10 至 3.14 的現代語法特性、型別安全與非同步開發。
55
55
  * **環境管理專家 (`skills/neo-python-manager`)**:智慧偵測與管理 Python 專案環境,支援 uv, Poetry, venv/pip 並提供自動化安裝建議。
56
56
 
57
- ### 7. Swift 開發專家
57
+ ### 6. Swift 開發專家
58
58
 
59
59
  * **Swift 5.0+ 專家 (`skills/neo-swift`)**:支援從基礎語法到 Swift 6 的現代開發模式,涵蓋 SwiftUI、Structured Concurrency、記憶體安全以及高效能 App 開發指引。
60
60
  * **SwiftUI 專家 (`skills/neo-swift-ui`)**:支援 iOS 16.0+ 與 Swift 5.0+ 的現代開發模式,專注於 NavigationStack、Observation 框架、資料流架構及高效能視圖設計。
61
61
 
62
- ### 8. JavaScript 開發專家
62
+ ### 7. JavaScript 開發專家
63
63
 
64
64
  * **JavaScript 現代語法專家 (`skills/neo-javascript`)**:跨版本 JavaScript 專家 (ES6 - ES2025+),專注於現代化語法、模組系統與高效能開發模式。
65
65
 
66
+ ### 8. TypeScript 開發專家
67
+
68
+ * **TypeScript 現代語法與型別安全 (`skills/neo-typescript`)**:專注於極致的型別安全、高可維護性與進階元程式設計(Meta-programming)。
69
+ * **型別系統防線**:涵蓋進階條件型別 (Conditional Types)、映射型別 (Mapped Types) 與樣板字面值型別。
70
+ * **互通性與配置最佳化**:深入調校 `tsconfig.json` 編譯選項,並徹底解決複雜的 ESM/CJS 互通性陷阱與執行期崩潰問題。
71
+ * **泛型約束設計**:引導設計高靈活度的泛型與變量 (Variance) 處理。
72
+
66
73
  ### 9. Vue 開發專家
67
74
 
68
75
  * **Vue 3 現代開發專家 (`skills/neo-vue`)**:專注於 Vue 3 Composition API (`<script setup>`)、Pinia 狀態管理與 Vue Router 4。嚴格遵循官方 Style Guide 與最佳實踐,並提供反模式 (Anti-Patterns) 的避坑指引。
@@ -237,6 +244,7 @@ npx -p @moon791017/neo-skills install-system-instructions \
237
244
  | **需求釐清與規格化** | `我想做一個電商網站` |
238
245
  | **全方位程式碼審查** | `幫我 code review 剛才的修改` |
239
246
  | **生成 C# Interface** | `幫我針對這個 class 產生介面` |
247
+ | **TypeScript 型別設計與互通性** | `解決 tsconfig 還有 ESM/CJS 互通性的問題`、`幫我寫一個強型別的泛型工具` |
240
248
  | **技術解析與架構洞察** | `分析這個專案的架構` |
241
249
  | **AI 開發流程健檢** | `幫我檢查這個專案怎麼讓 AI 助手開發得更穩、更安全` |
242
250
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moon791017/neo-skills",
3
- "version": "1.0.41",
3
+ "version": "1.0.42",
4
4
  "type": "module",
5
5
  "description": "Neo Skills: A Universal Expert Agent Extension",
6
6
  "homepage": "https://neo-blog-iota.vercel.app/",
@@ -0,0 +1,43 @@
1
+ ---
2
+ name: neo-typescript
3
+ description: >
4
+ Use this skill when asked to write, review, debug, or architect TypeScript code, configure tsconfig.json compiler options, resolve ESM/CJS interop issues, optimize generics, or apply advanced conditional, mapped, and template literal type operators. Trigger even if the user just asks generic TS compiler or type compatibility questions.
5
+ license: MIT
6
+ metadata:
7
+ author: ant-gravity-devs
8
+ version: "1.0.0"
9
+ ---
10
+
11
+ # Neo TypeScript Expert Skill
12
+
13
+ This skill guides the AI Agent to write code that adheres to the strictest type safety, high maintainability, and advanced meta-programming flexibility, while thoroughly preventing runtime issues such as ESM/CJS interoperability pitfalls.
14
+
15
+ ## 💡 Gotchas
16
+ * **Aliasing Writable Reference Bypasses Readonly**: In TypeScript, `readonly` only restricts the assignment to the property itself. The internal members of the referenced object/array remain mutable. Furthermore, a readonly object can be assigned to a writable alias, which completely bypasses compiler readonly checks.
17
+ * **Fatal Crash via Partial esModuleInterop**: Enabling `allowSyntheticDefaultImports` without `esModuleInterop` allows code to pass compile-time type checks but causes an immediate runtime crash (TypeError: default is not a function) due to the lack of `__importDefault` emit helpers in transpile output.
18
+ * **Double Default Trap for Library Creators**: Using `export default` in libraries forces Node.js ESM consumers to call `.default()` to access the module. The golden standard is to completely abandon `export default` and adopt `export =` or named exports instead.
19
+
20
+ ## 📋 Static Code & Type Safety Review SOP
21
+
22
+ When asked to write, modify, refactor, or review TypeScript code, strictly execute the following workflow:
23
+
24
+ ### Step 1 — Project Environment Perception (Perceive)
25
+ 1. Inspect the project's `tsconfig.json` settings, focusing specifically on the configuration of `"strict": true`, `"strictNullChecks"`, and `"strictFunctionTypes"`.
26
+ 2. Identify the target module format and resolution mechanism (`"moduleResolution"`).
27
+
28
+ ### Step 2 — Core Type Routing (Reason)
29
+ Based on the specific technical domain of the task, **progressively disclose** and load the corresponding reference files in the skill. Do not load all files at once to save context token space:
30
+ * **Basics, Narrowing, Classes, & Function Design** ➡️ Load [type-system-basics.md](references/type-system-basics.md)
31
+ * **Generic Constraints, Variance, & Advanced Types from Types** ➡️ Load [advanced-meta-types.md](references/advanced-meta-types.md)
32
+ * **Structural Compatibility, Decorators, & ESM/CJS Interop** ➡️ Load [compatibility-and-interop.md](references/compatibility-and-interop.md)
33
+
34
+ ### Step 3 — Precise Code Generation & Review (Act)
35
+ 1. Ensure all generated or modified code strictly adheres to the loaded reference guidelines (e.g., never declare optional callback parameters, ensure generic type parameters appear at least twice to establish correlation).
36
+ 2. For advanced type generation, recommend clear unit test assertions based on the evals configuration.
37
+
38
+ ---
39
+
40
+ ## 🛠️ Available Resources (Relative Paths)
41
+ * [Type System Basics Guide](references/type-system-basics.md)
42
+ * [Advanced Meta Types Guide](references/advanced-meta-types.md)
43
+ * [Compatibility and Interop Guide](references/compatibility-and-interop.md)
@@ -0,0 +1,66 @@
1
+ [
2
+ {
3
+ "query": "How do distributive conditional types work in TypeScript?",
4
+ "should_trigger": true
5
+ },
6
+ {
7
+ "query": "My Node project crashes with TypeError: default is not a function when loading a CJS library in ESM. How do I fix esModuleInterop?",
8
+ "should_trigger": true
9
+ },
10
+ {
11
+ "query": "Can you review my TypeScript code for type compatibility and bivariance issues?",
12
+ "should_trigger": true
13
+ },
14
+ {
15
+ "query": "Explain how to remove readonly modifiers from all keys in a mapped type.",
16
+ "should_trigger": true
17
+ },
18
+ {
19
+ "query": "I am configuring my tsconfig.json compilerOptions, what moduleResolution should I choose for Webpack/Vite?",
20
+ "should_trigger": true
21
+ },
22
+ {
23
+ "query": "How to design a type-safe event listener using template literal types for a watched object?",
24
+ "should_trigger": true
25
+ },
26
+ {
27
+ "query": "Why does my readonly property get mutated through an aliased writable reference?",
28
+ "should_trigger": true
29
+ },
30
+ {
31
+ "query": "How do I implement a nominal type simulation using private properties in TypeScript classes?",
32
+ "should_trigger": true
33
+ },
34
+ {
35
+ "query": "How to write a fibonacci function in JavaScript?",
36
+ "should_trigger": false
37
+ },
38
+ {
39
+ "query": "What is the weather today in Taipei?",
40
+ "should_trigger": false
41
+ },
42
+ {
43
+ "query": "Can you design a simple React component that renders a button with styled-components?",
44
+ "should_trigger": false
45
+ },
46
+ {
47
+ "query": "What is the difference between let and const in plain JS?",
48
+ "should_trigger": false
49
+ },
50
+ {
51
+ "query": "How to center a div horizontally and vertically using CSS flexbox?",
52
+ "should_trigger": false
53
+ },
54
+ {
55
+ "query": "Write a python script that parses a CSV and sends it to database.",
56
+ "should_trigger": false
57
+ },
58
+ {
59
+ "query": "What is the difference between null and undefined in JavaScript?",
60
+ "should_trigger": false
61
+ },
62
+ {
63
+ "query": "Can you explain how ECMAScript decorators Stage 3 standard works in plain JS?",
64
+ "should_trigger": false
65
+ }
66
+ ]
@@ -0,0 +1,27 @@
1
+ {
2
+ "skill_name": "neo-typescript",
3
+ "evals": [
4
+ {
5
+ "id": 1,
6
+ "prompt": "How do I write a Mapped Type that iterates over T, converts all its properties to readonly, and capitalizes key names prefixed with 'get'? For example, converting { name: string } to { readonly getName: () => string }.",
7
+ "expected_output": "Provide an advanced meta-programming solution using Mapped Types combined with Key Remapping `as` and `Capitalize`, including complete type code and validation examples.",
8
+ "assertions": [
9
+ "Output contains Mapped Type code using 'as' to rename property keys",
10
+ "Type expressions correctly use both 'readonly' and 'Capitalize' modifiers",
11
+ "Provide a concrete Example structure to validate the mapped type",
12
+ "The solution explicitly points out the gotcha of needing '& string' during key remapping"
13
+ ]
14
+ },
15
+ {
16
+ "id": 2,
17
+ "prompt": "My project is an npm library that needs to support both CommonJS and ESM consumers. How do I safely export my main entry point to prevent users from encountering Double Default or default is not a function runtime crashes?",
18
+ "expected_output": "Explain the underlying cause of CommonJS and ESM dual-module loading conflicts, strongly recommend completely abandoning `export default`, and provide the golden solution of using `export =` and Named Exports.",
19
+ "assertions": [
20
+ "The solution explicitly mentions the magic emit helpers injected by esModuleInterop",
21
+ "Explicitly warn about the fatal runtime crash risk of enabling allowSyntheticDefaultImports alone",
22
+ "Provide clear code examples of TypeScript-specific 'export =' or Named Exports",
23
+ "Explain that library creators must avoid export default to prevent Double Default traps"
24
+ ]
25
+ }
26
+ ]
27
+ }
@@ -0,0 +1,124 @@
1
+ # TypeScript Advanced Meta-Programming Reference
2
+
3
+ This document serves as the advanced meta-programming and type manipulation guide for the `neo-typescript` skill, covering generic variance, keyof/typeof, indexed access, conditional types, mapped types, and template literal type operations.
4
+
5
+ ---
6
+
7
+ ## 1. Generic Variance (Variance Annotations)
8
+
9
+ Type variance describes the relationship between `Box<Cat>` and `Box<Animal>` when `Cat` is a subtype of `Animal`.
10
+
11
+ * **Covariance (out modifier)**:
12
+ If `Box<T>` only acts as a **Producer** (e.g., only has `make(): T`), the relationship is co-directional (`Box<Cat>` is assignable to `Box<Animal>`). Declare with `out T`.
13
+ * **Contravariance (in modifier)**:
14
+ If `Box<T>` only acts as a **Consumer** (e.g., only has `consume(x: T): void`), the relationship is reversed (a consumer that handles all Animals can safely handle Cats). Declare with `in T`.
15
+ * **Invariance (in out modifier)**:
16
+ If a type acts as both producer and consumer, the relationship is bi-directionally locked.
17
+ * > [!IMPORTANT]
18
+ > TypeScript is a structural type system and automatically infers structural variance. **Manual `in`/`out` annotations are purely for compiler optimization and circular type debugging; they never alter basic structural comparison behavior**.
19
+
20
+ ---
21
+
22
+ ## 2. keyof & typeof Operators
23
+
24
+ * **`keyof` Index Signature Behavior**:
25
+ Returns a union of literal keys. Note that if an object contains an index signature, such as `Mapish = { [k: string]: boolean }`, `keyof Mapish` returns **`string | number`** (because JavaScript keys are coerced to strings).
26
+ * **`typeof` Physical Limitations**:
27
+ Captures the precise type of a value or property identifier. **Can only be used on identifiers (variable names, property paths)**. Never use `typeof` on function execution calls or dynamic expressions (e.g., `typeof func()` is invalid; use `typeof func` with `ReturnType` instead).
28
+
29
+ ---
30
+
31
+ ## 3. Indexed Access Types
32
+
33
+ * `T[K]` lookup allows precise type querying in the type space.
34
+ * **Element Capture**: Use `MyArray[number]` to extract the exact element object type from array or tuple literals.
35
+ * **Lookup Limitations**: The index `K` **must be a type**. Never pass a runtime variable value. If you need to refer to a variable name, extract its type using `typeof` first: `Person[typeof key]`.
36
+
37
+ ---
38
+
39
+ ## 4. Conditional Types & infer Inference
40
+
41
+ Enables delayed type resolution and conditional branches via `T extends U ? X : Y`.
42
+
43
+ ### Declarative Inference via `infer`:
44
+ Declare a new variable in the true branch of an `extends` comparison, allowing the compiler to automatically capture the type:
45
+ ```ts
46
+ // Extract the resolved type of a Promise
47
+ type Await<T> = T extends Promise<infer U> ? U : T;
48
+
49
+ // Extract return type of a function
50
+ type GetReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
51
+ ```
52
+ > [!WARNING]
53
+ > When using `infer` to extract return types from overloaded functions, **TypeScript will infer from the very last overload signature (which is typically the most permissive, catch-all implementation)**.
54
+
55
+ ### Distributive Conditional Types:
56
+ * **Trigger Condition**: When a conditional type acts on a **bare type parameter** and a **union type** is passed as the argument, the conditional type automatically distributes across the union:
57
+ `ToArray<string | number>` ➡️ `string[] | number[]`.
58
+ * **Blocking Distribution (Non-distributive wrapping)**:
59
+ To preserve the union as a whole, **wrap both sides of the comparison in square brackets `[]`**, which disrupts the bare type parameter status:
60
+ ```ts
61
+ type ToArrayNonDist<T> = [T] extends [any] ? T[] : never;
62
+ // ToArrayNonDist<string | number> infers as (string | number)[]
63
+ ```
64
+
65
+ ---
66
+
67
+ ## 5. Mapped Types & Modifier Operations
68
+
69
+ Mapped types construct new object types by iterating over a set of keys: `[P in keyof T]: T[P]`.
70
+
71
+ ### Mapping Modifiers:
72
+ Add or remove `readonly` and `?` modifiers using `+` (optional) or `-` prefixes:
73
+ ```ts
74
+ // Remove readonly, turning a readonly object into writable
75
+ type Mutable<T> = {
76
+ -readonly [P in keyof T]: T[P];
77
+ };
78
+
79
+ // Remove optionality, forcing all properties to be implemented
80
+ type Concrete<T> = {
81
+ [P in keyof T]-?: T[P];
82
+ };
83
+ ```
84
+
85
+ ### Key Remapping via `as`:
86
+ Use `as` to rename keys, exclude properties with `Exclude` and `never`, or iterate over arbitrary configuration unions:
87
+ ```ts
88
+ // Rename keys: prefix with 'get' and capitalize the property name
89
+ type Getters<T> = {
90
+ [P in keyof T as `get${Capitalize<string & P>}`]: () => T[P];
91
+ };
92
+
93
+ // Filter properties: exclude the 'kind' property
94
+ type OmitKind<T> = {
95
+ [P in keyof T as Exclude<P, "kind">]: T[P];
96
+ };
97
+ ```
98
+
99
+ ---
100
+
101
+ ## 6. Template Literal Types
102
+
103
+ Template literal types allow string interpolation. If a union type is placed inside the interpolation slot, TypeScript automatically performs a **Cartesian product expansion**:
104
+ ```ts
105
+ type Lang = "en" | "ja";
106
+ type Event = "welcome" | "footer";
107
+ type LocaleID = `${Lang}_${Event}_id`;
108
+ ```
109
+
110
+ ### Strong-Typed Event Listener (Watched Object Pattern):
111
+ Combining template literals, generics, and indexed access enables a 100% type-safe event subscription source:
112
+ ```ts
113
+ type PropEventSource<T> = {
114
+ on<K extends string & keyof T>
115
+ (eventName: `${K}Changed`, callback: (newValue: T[K]) => void): void;
116
+ };
117
+
118
+ // Used with makeWatchedObject to automatically infer newValue in callbacks
119
+ declare function makeWatchedObject<T>(obj: T): T & PropEventSource<T>;
120
+ ```
121
+
122
+ ### Intrinsic String Manipulation Types:
123
+ Built-in compiler helper types:
124
+ * `Uppercase<T>`, `Lowercase<T>`, `Capitalize<T>`, `Uncapitalize<T>`.
@@ -0,0 +1,82 @@
1
+ # TypeScript Compatibility & Module Interoperability Reference
2
+
3
+ This document serves as the guide for type compatibility rules and module loading interoperability for the `neo-typescript` skill, covering structural compatibility, function parameter variance, decorator standards, and ESM/CJS interop rules.
4
+
5
+ ---
6
+
7
+ ## 1. Structural Compatibility & Parameter Variance (Type Compatibility)
8
+
9
+ TypeScript's type checking is based on a **structural type system**—compatibility is determined solely by the shape of the members.
10
+
11
+ ### Function Parameter Bivariance:
12
+ * *Type Theory*: Function parameter comparison should be **contravariant**. However, to support common JavaScript patterns (like event handlers and array covariance), TypeScript historically allows parameters to be bivariant by default.
13
+ * **`strictFunctionTypes` Safety Valve**:
14
+ Enabling `strictFunctionTypes: true` forces function parameters to undergo strict **contravariant** checks, eliminating runtime crashes where a parameter is too specialized.
15
+ * **The Single Exemption: Method Shorthand**:
16
+ > [!IMPORTANT]
17
+ > To maintain compatibility with common OOP patterns, **under `strictFunctionTypes: true`, shorthand method declarations (e.g., `method(arg: T): void`) remain bivariant**.
18
+ > Only property-based function signatures (e.g., `method: (arg: T) => void`) are subjected to strict contravariant checks!
19
+ > For maximum type safety in libraries, prefer property-based function signatures.
20
+
21
+ ---
22
+
23
+ ## 2. New Stage 3 Decorators vs. Experimental
24
+
25
+ TypeScript 5.0 introduced native support for ECMAScript Stage 3 decorators, which differ fundamentally in architecture from the old legacy decorators:
26
+
27
+ ### Core Comparison:
28
+
29
+ | Feature | Legacy Experimental Decorators (`experimentalDecorators: true`) | New Stage 3 Standard Decorators (TS 5.0+ Native) |
30
+ | :--- | :--- | :--- |
31
+ | **Parameters** | Receives `(target, propertyKey, descriptor)` | Receives `(value, context)` |
32
+ | **Mutation Behavior** | Directly **mutates** the passed descriptor object | **No mutation**. Returns a **brand new replacement function or value** |
33
+ | **Private Members** | **No support** for JavaScript private fields (`#field`) | **Full support** for private fields and private methods |
34
+ | **Metadata Dependency** | Relies heavily on `reflect-metadata` reflection | Relies on the TC39 standard context without metadata coupling |
35
+
36
+ *Standard Method Decorator Example*:
37
+ ```ts
38
+ function loggedMethod<This, Args extends any[], Return>(
39
+ target: (this: This, ...args: Args) => Return,
40
+ context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>
41
+ ) {
42
+ return function (this: This, ...args: Args): Return {
43
+ console.log(`Calling method: ${String(context.name)}`);
44
+ return target.call(this, ...args);
45
+ };
46
+ }
47
+ ```
48
+
49
+ ---
50
+
51
+ ## 3. ESM/CJS Interoperability & Dual Module Issues (Interop)
52
+
53
+ The most notorious and difficult-to-debug pain point in modern Node.js and bundler toolchains.
54
+
55
+ ### 1. The Real Impact of `moduleResolution`:
56
+ * `node16` / `nodenext`:
57
+ Enforces strict Node.js native ESM rules: **relative ESM imports must include file extensions (e.g., `import "./add.js"` even if the source is `.ts`)**, and package.json exports conditional queries are strictly verified.
58
+ * `bundler`:
59
+ Designed for bundlers like Vite, Webpack, or esbuild. Allows omitting file extensions and resolving modules using bundler rules, bypassing strict Node.js runtime resolution limits.
60
+
61
+ ### 2. `esModuleInterop` & `allowSyntheticDefaultImports` Emit Helpers:
62
+ Conflicts arise when an ES module attempts to `import` a pure CommonJS module (which lacks a `default` export and exposes a flat `module.exports` object).
63
+ * **The Magic of `esModuleInterop: true`**:
64
+ Enabling this flag causes `tsc` to inject `__importDefault` and `__importStar` emit helper wrappers in transpiled JS output.
65
+ `__importDefault` checks if the imported module has `__esModule: true`. If not, it **automatically generates a `{ default: exports }` wrapper object**, enabling `import x from "x"` to successfully grab the CJS module.
66
+ * **The Danger of Standalone `allowSyntheticDefaultImports`**:
67
+ This flag only tells the **type checker** to assume the target has a synthetic default export.
68
+ > [!CAUTION]
69
+ > Enabling `allowSyntheticDefaultImports` without `esModuleInterop` is **extremely dangerous**!
70
+ > The project will compile successfully, but it will **crash at runtime** with `TypeError: default is not a function` because the actual transpile output lacks the essential emit helpers. Always enable `esModuleInterop`.
71
+
72
+ ---
73
+
74
+ ## 4. Legacy Compatibility Features
75
+
76
+ * **Enum Tree-Shaking Issues**:
77
+ * Standard Enums compile into immediate IIFE double-mapped objects. Bundlers cannot statically verify if the IIFE has side-effects, so **standard enums are never tree-shaken**.
78
+ * **Golden Solution**: Unless you need reverse mapping (value to key), **always prefer `const enum`**, which erases the IIFE and inlines constant values directly.
79
+ * **Namespaces**:
80
+ Legacy internal modules predating ES Modules. They compile into global scope mutations and should be avoided in modern codebases in favor of standard `import`/`export`.
81
+ * **Mixins**:
82
+ Emulated using generic class factory patterns `function Scale<TBase extends Constructor>(Base: TBase)` to simulate multiple inheritance behavior.
@@ -0,0 +1,75 @@
1
+ # TypeScript Type System Basics Reference
2
+
3
+ This document serves as the foundational guide for the `neo-typescript` skill, covering type system basics, everyday types, control flow analysis for narrowing, and fundamental function and class design specifications.
4
+
5
+ ---
6
+
7
+ ## 1. Static Compilation & Core Mechanics (The Basics)
8
+
9
+ * **Non-exception Failures**: TypeScript elevates runtime-silent JavaScript failures (such as typos, uncalled functions like `Math.random < 0.5`, or dead logic) to compile-time errors.
10
+ * **Type Erasure**: All type annotations, interfaces, and type aliases are **100% erased** during transpilation to JavaScript. The type system has absolutely zero footprint or effect on runtime behavior.
11
+ * **Downleveling**: `tsc` automatically transpiles modern ECMAScript features to older versions (e.g., ES5, ES6) based on the `"target"` configuration in `tsconfig.json`.
12
+ * **Strictness Flags**: Enabling `"strict": true` turns on core defensive flags, including `noImplicitAny` (disallows implicit any) and `strictNullChecks` (treats Null and Undefined as independent types).
13
+
14
+ ---
15
+
16
+ ## 2. Everyday Type Guidelines (Everyday Types)
17
+
18
+ * **Primitive Types**: Always use lowercase `string`, `number`, and `boolean`. **Never** use uppercase wrapper objects like `String`, `Number`, or `Boolean` as they represent wrapper objects and invite type compatibility bugs.
19
+ * **Contextual Typing**: Anonymous functions placed in positions where TypeScript can infer their usage automatically type their arguments without manual annotations (e.g., `names.forEach(s => ...)` infers `s` as string).
20
+ * **Type Alias vs. Interface Decision**:
21
+ * `interface`: Supports **declaration merging**. It features better compiler caching and is the preferred choice for defining object shapes.
22
+ * `type`: Cannot be merged once declared, but is ideal for union types, tuples, and mapped types.
23
+ * **Literal Inference & `as const`**: Object literal properties are widened to their base types by default. To lock them as readonly and exact literal types, suffix the object with `as const`:
24
+ ```ts
25
+ const req = { url: "https://example.com", method: "GET" } as const;
26
+ // req.method is strictly typed as "GET"
27
+ ```
28
+
29
+ ---
30
+
31
+ ## 3. Control Flow Analysis & Narrowing
32
+
33
+ Type narrowing is the control flow analysis where the compiler traces program paths to deduce the most precise types at specific locations.
34
+
35
+ ### Core Type Guards:
36
+ * `typeof` guard: Beware of the historical JS quirk where `typeof null === "object"`.
37
+ * Truthiness narrowing: Use `&&` or `!!` to filter out `null` or `undefined`.
38
+ * Equality narrowing: Perform `===` or `!==` comparisons. *Tip*: `x != null` (loose inequality) filters out both `null` and `undefined` in one step.
39
+ * `in` guard: Checks if a property exists on an object. Note that optional properties will still appear in both branches after narrowing.
40
+ * `instanceof` guard: Checks instance constructors.
41
+
42
+ ### User-Defined Type Predicates:
43
+ To encapsulate narrowing logic in helper functions, declare the return type as `parameterName is Type`:
44
+ ```ts
45
+ function isFish(pet: Fish | Bird): pet is Fish {
46
+ return (pet as Fish).swim !== undefined;
47
+ }
48
+ ```
49
+
50
+ ### Discriminated Unions & Exhaustiveness Checking:
51
+ Use a shared literal tag property (e.g., `kind`) across union members and perform exhaustiveness checking in `switch` blocks using `never` to ensure compiler warnings are raised when new members are added to the union:
52
+ ```ts
53
+ const _exhaustiveCheck: never = shape;
54
+ ```
55
+
56
+ ---
57
+
58
+ ## 4. High-Quality Function Design Rules (Functions)
59
+
60
+ * **Call & Construct Signatures**: Parameter names are **mandatory** in function type expressions. Writing `(string) => void` creates a parameter named `string` with type `any`.
61
+ * **Three Rules for Excellent Generics**:
62
+ 1. **Push Type Parameters Down**: Use the type parameter directly in the signature to preserve the exactness of the return type.
63
+ 2. **Ensure Type Parameters Appear at Least Twice**: If a parameter appears only once, it does not establish a correlation between values and should be replaced with a regular type annotation.
64
+ 3. **Minimize Type Parameters**: Avoid introducing redundant type parameters that add no distinct constraints.
65
+ * **Optional Parameter Callback Ban**:
66
+ **Never** declare callback parameters as optional (e.g., `callback: (arg: T, index?: number) => void`). This forces callback implementors to write redundant `undefined` checks. Keep them required; JavaScript automatically discards extra arguments anyway.
67
+ * **Relaxed void Assignability**: A callback function whose contextual type expects a `void` return is **allowed to return any other value** (which is safely ignored). This enables callbacks like `src.forEach(el => dst.push(el))` to compile successfully.
68
+
69
+ ---
70
+
71
+ ## 5. Classes & Nominal Simulation Basics (Classes)
72
+
73
+ * **Parameter Properties**: Suffixing constructor arguments with access modifiers (like `public readonly x`) automatically declares them as instance fields and performs initialization, eliminating boilerplate code.
74
+ * **this Parameter Annotation**: Declaring the first parameter as `this: ClassName` statically binds the call context, preventing runtime bugs when methods are assigned to variables and lose their `this` context.
75
+ * **Nominal Simulation**: Structural typing only compares instance member shapes. However, if a class contains `private` or `protected` members, assignment compatibility strictly requires those members to originate from **"the exact same class declaration inheritance tree"**. Classes with identical shapes but different roots are rejected, simulating nominal safety.