
typescript-magician
熱門設計複雜的泛型型別、將 `any` 型別重構為嚴謹的替代方案、建立型別守衛與工具型別,並解決 TypeScript 編譯器錯誤。當使用者詢問 TypeScript (TS) 型別、泛型、型別推導、型別守衛、移除 `any` 型別、嚴謹型別(strict typing)、型別錯誤、`infer`、`extends`、條件型別、對映型別(mapped types)、樣板字面型別(template literal types)、品牌/不透明型別(branded/opaque types),或是像 `Partial`、`Record`、`ReturnType` 及 `Awaited` 等工具型別時使用。
1894星標
150分支
更新於 2026/8/3
SKILL.md
唯讀
名稱
typescript-magician
描述
設計複雜的泛型型別、將 `any` 型別重構為嚴謹的替代方案、建立型別守衛與工具型別,並解決 TypeScript 編譯器錯誤。當使用者詢問 TypeScript (TS) 型別、泛型、型別推導、型別守衛、移除 `any` 型別、嚴謹型別(strict typing)、型別錯誤、`infer`、`extends`、條件型別、對映型別(mapped types)、樣板字面型別(template literal types)、品牌/不透明型別(branded/opaque types),或是像 `Partial`、`Record`、`ReturnType` 及 `Awaited` 等工具型別時使用。
何時使用
在以下情境使用此 Skill:
- 處理 TypeScript 錯誤與型別挑戰
- 從程式碼庫中消除
any型別 - 解決複雜的泛型與型別推導問題
- 需要嚴謹型別(strict typing)時
操作說明
當此 Skill 被呼叫時:
- 在進行修改前,先執行
tsc --noEmit擷取完整的錯誤輸出 - 找出型別問題的根本原因(如不穩健的型別推導、缺少型別約束、隱式
any等) - 運用 TypeScript 進階功能打造精準且型別安全的解決方案
- 用適當的型別消除所有
any型別——並驗證每個替換依然符合呼叫端的需求 - 再次執行
tsc --noEmit,確認修正後能無錯順利編譯
能力涵蓋:
- 進階泛型與條件型別
- 樣板字面型別與對映型別
- 工具型別與型別操作
- 品牌型別(Brand types)與名義型別(Nominal typing)
- 複雜的型別推導模式
- 變異性(Variance)與分發規則(Distribution rules)
- 模組擴充(Module augmentation)與宣告合併(Declaration merging)
針對每個 TypeScript 挑戰:
- 解釋問題背後的型別理論
- 在適用時提供多種解決方案
- 展示修改前/後的型別結構比較
- 提供完整的型別測試
- 確保完整的 IntelliSense 自動補全支援
快速範例
使用泛型消除 any
修改前
function getProperty(obj: any, key: string): any {
return obj[key];
}
修改後
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
// getProperty({ name: "Alice" }, "name") → inferred as string ✓
收窄不確定的 API 回應型別
修改前
async function fetchUser(): Promise<any> {
const res = await fetch("/api/user");
return res.json();
}
修改後
interface User { id: number; name: string }
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
"name" in value
);
}
async function fetchUser(): Promise<User> {
const res = await fetch("/api/user");
const data: unknown = await res.json();
if (!isUser(data)) throw new Error("Invalid user shape");
return data;
}
參考指南
請參閱個別規則檔案以取得詳細說明與程式碼範例:
核心模式
- rules/as-const-typeof.md - 使用
as const與typeof從執行階段數值推導型別 - rules/array-index-access.md - 使用
[number]索引存取陣列元素型別 - rules/utility-types.md - 內建工具型別:Parameters、ReturnType、Awaited、Omit、Partial、Record
進階泛型
- rules/generics-basics.md - 泛型型別、約束與推導的基礎概念
- rules/builder-pattern.md - 具備鏈結方法的型別安全建造者模式(Builder Pattern)
- rules/deep-inference.md - 使用 F.Narrow 與 const 型別參數實現深層型別推導
型別層級程式設計
- rules/conditional-types.md - 用於型別層級 if/else 邏輯的條件型別
- rules/infer-keyword.md - 使用
infer在條件型別中擷取型別 - rules/template-literal-types.md - 型別層級的字串操作
- rules/mapped-types.md - 透過轉換既有型別屬性來建立新型別
型別安全模式
- rules/opaque-types.md - 用於型別安全識別碼的品牌型別(Brand types)與不透明型別(Opaque types)
- rules/type-narrowing.md - 透過控制流程分析進行型別收窄
- rules/function-overloads.md - 針對複雜函式簽章使用函式多載(Function Overloads)
偵錯
- rules/error-diagnosis.md - 診斷與理解 TypeScript 型別錯誤的策略





