typescript-pro

typescript-pro

熱門

實作進階 TypeScript 型別系統,建立自訂型別守衛(Type Guards)、工具型別(Utility Types)與品牌型別(Branded Types),並配置 tRPC 實現端到端型別安全。當開發需要進階泛型、條件型別、對映型別、可辨識聯集(Discriminated Unions)、Monorepo 架構配置或透過 tRPC 達成全端型別安全的 TypeScript 應用程式時使用。

1.1萬星標
953分支
更新於 2026/5/20
SKILL.md
唯讀
名稱
typescript-pro
描述

實作進階 TypeScript 型別系統,建立自訂型別守衛(Type Guards)、工具型別(Utility Types)與品牌型別(Branded Types),並配置 tRPC 實現端到端型別安全。當開發需要進階泛型、條件型別、對映型別、可辨識聯集(Discriminated Unions)、Monorepo 架構配置或透過 tRPC 達成全端型別安全的 TypeScript 應用程式時使用。

TypeScript Pro

核心工作流程

  1. 分析型別架構 — 審視 tsconfig、型別覆蓋率與建置效能
  2. 設計型別優先(Type-First)的 API — 建立品牌型別、泛型與工具型別
  3. 具備型別安全地進行實作 — 撰寫型別守衛、可辨識聯集與條件型別;在繼續之前執行 tsc --noEmit 擷取型別錯誤
  4. 最佳化建置程序 — 配置專案參考(Project References)、遞增編譯(Incremental Compilation)與 Tree Shaking;變更後重新執行 tsc --noEmit 以確認零錯誤
  5. 測試型別 — 使用如 type-coverage 等工具確認型別覆蓋率;驗證所有公開 API 皆具備明確的傳回型別;反覆執行步驟 3–4 直到所有檢查通過

參考指南

根據情境載入詳細指引:

主題 參考文件 載入時機
進階型別 references/advanced-types.md 泛型、條件型別、對映型別、樣板字面常數型別
型別守衛 references/type-guards.md 型別收窄(Type Narrowing)、可辨識聯集、斷言函式
工具型別 references/utility-types.md Partial、Pick、Omit、Record 或自訂工具型別
設定配置 references/configuration.md tsconfig 選項、嚴格模式、專案參考
設計模式 references/patterns.md 建造者模式、工廠模式、型別安全 API

程式碼範例

品牌型別 (Branded Types)

// 領域模型使用的品牌型別
type Brand<T, B extends string> = T & { readonly __brand: B };
type UserId  = Brand<string, "UserId">;
type OrderId = Brand<number, "OrderId">;

const toUserId  = (id: string): UserId  => id as UserId;
const toOrderId = (id: number): OrderId => id as OrderId;

// 使用方式 — 在編譯期防止意外混淆不同的 ID
function getOrder(userId: UserId, orderId: OrderId) { /* ... */ }

可辨識聯集與型別守衛 (Discriminated Unions & Type Guards)

type LoadingState = { status: "loading" };
type SuccessState = { status: "success"; data: string[] };
type ErrorState   = { status: "error";   error: Error };
type RequestState = LoadingState | SuccessState | ErrorState;

// 型別述語守衛(Type Predicate Guard)
function isSuccess(state: RequestState): state is SuccessState {
  return state.status === "success";
}

// 搭配可辨識聯集進行完備性檢查的 switch(Exhaustive Switch)
function renderState(state: RequestState): string {
  switch (state.status) {
    case "loading": return "Loading…";
    case "success": return state.data.join(", ");
    case "error":   return state.error.message;
    default: {
      const _exhaustive: never = state;
      throw new Error(`Unhandled state: ${_exhaustive}`);
    }
  }
}

自訂工具型別 (Custom Utility Types)

// 深度唯讀(Deep Readonly)— 不可變的巢狀物件
type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
};

// 嚴格要求在一組 Key 中只能恰好存在一個
type RequireExactlyOne<T, Keys extends keyof T = keyof T> =
  Pick<T, Exclude<keyof T, Keys>> &
  { [K in Keys]-?: Required<Pick<T, K>> & Partial<Record<Exclude<Keys, K>, never>> }[Keys];

推薦的 tsconfig.json

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitOverride": true,
    "exactOptionalPropertyTypes": true,
    "isolatedModules": true,
    "declaration": true,
    "declarationMap": true,
    "incremental": true,
    "skipLibCheck": false
  }
}

開發規範與限制

必須做到 (MUST DO)

  • 啟用包含所有編譯器旗標的嚴格模式(Strict Mode)
  • 採用型別優先(Type-first)的 API 設計
  • 實作品牌型別用於領域模型建立
  • 使用 satisfies 運算子進行型別驗證
  • 為狀態機建立可辨識聯集
  • 使用帶有型別述語(Type Predicate)的 Annotated 模式
  • 為函式庫產生聲明檔(Declaration files)
  • 針對型別推導(Type Inference)進行最佳化

切勿做到 (MUST NOT DO)

  • 在未經合理說明的情況下使用明確的 any
  • 忽略公開 API 的型別覆蓋率
  • 混合僅型別匯入(Type-only import)與數值匯入(Value import)
  • 停用嚴格 Null 檢查(Strict Null Checks)
  • 在非必要情況下使用 as 斷言
  • 忽視編譯器效能警告
  • 遺漏聲明檔(Declaration file)的產生
  • 使用 Enum(建議改用帶有 as const 的常數物件)

輸出範本

實作 TypeScript 功能時,請提供:

  1. 型別定義(Interface、Type、Generics)
  2. 包含型別守衛的實作
  3. 必要時提供 tsconfig 設定
  4. 簡短說明型別設計決策

知識參考

TypeScript 5.0+、泛型、條件型別、對映型別、樣板字面常數型別、可辨識聯集、型別守衛、品牌型別、tRPC、專案參考、遞增編譯、聲明檔、const 斷言、satisfies 運算子

Documentation