前端 TypeScript 型別技能
目的:根據 frontend/types/index.ts 中的現有模式,建立 TypeScript 型別定義的指南。
概述
所有 TypeScript 型別都定義在 frontend/types/index.ts 中。型別與後端 API 回應結構一致,並為前端應用程式提供型別安全。
來自 frontend/types/index.ts 的型別模式
1. 使用者型別
export interface User {
id: string;
email: string;
name: string;
createdAt?: string;
updatedAt?: string;
}
export interface UserCredentials {
email: string;
password: string;
}
export interface UserSignupData extends UserCredentials {
name: string;
}
模式:
- 物件型別使用
interface - 可選欄位標記
? - 使用
extends進行型別繼承 - 前端型別使用駝峰命名法(即使後端使用蛇形命名法)
2. 任務型別
export type TaskStatus = "pending" | "completed";
export type TaskPriority = "low" | "medium" | "high";
export interface Task {
id: number;
user_id: string;
title: string;
description?: string;
completed: boolean;
priority: TaskPriority;
due_date?: string;
tags: string[];
created_at: string;
updated_at: string;
}
export interface TaskFormData {
title: string;
description?: string;
priority?: TaskPriority;
due_date?: string;
tags?: string[];
}
export interface TaskQueryParams {
status?: "all" | "pending" | "completed";
sort?: "created" | "title" | "updated" | "priority" | "due_date";
search?: string;
page?: number;
limit?: number;
}
模式:
- 聯合型別(字串字面量)使用
type - 物件型別使用
interface - 匹配後端欄位名稱(API 欄位使用蛇形命名法,如
user_id、due_date、created_at) - 為表單資料建立獨立的型別(除了必要欄位外,其他皆為可選)
- 為查詢參數建立獨立的型別(全部可選)
3. API 回應型別
export interface ApiResponse<T = unknown> {
data?: T;
success: boolean;
message?: string;
error?: {
code: string;
message: string;
details?: unknown;
};
}
export interface PaginatedResponse<T> {
data: T[];
meta: {
total: number;
page: number;
limit: number;
totalPages: number;
};
}
模式:
- 使用泛型
<T>實現可重用結構 - 提供預設型別參數(
<T = unknown>) - 包含
success布林標記 - 包含可選的
data、message和error欄位 - 為帶有
meta物件的分頁回應建立獨立的型別
4. 認證型別
export interface AuthResponse {
success: boolean;
token: string;
user: User;
}
export interface Session {
user: User;
token: string;
expiresAt: number;
}
模式:
- 包含
success布林值 - 包含
token字串 - 包含
user物件(User 型別) - 為 session 包含
expiresAt時間戳記
5. 錯誤型別
export interface AppError {
message: string;
code?: string;
statusCode?: number;
field?: string;
}
export interface FormErrors {
[key: string]: string | undefined;
}
模式:
- 錯誤物件使用
interface - 可選欄位標記
? - 為動態物件型別使用索引簽名
[key: string](FormErrors)
6. UI 型別
export type LoadingState = "idle" | "loading" | "success" | "error";
export type ToastType = "success" | "error" | "warning" | "info";
export interface ToastMessage {
id: string;
type: ToastType;
message: string;
duration?: number;
}
模式:
- 聯合型別(字串字面量)使用
type - 物件型別使用
interface - 包含
id以進行唯一標識 - 可選欄位標記
?
7. 匯出/匯入型別
export type ExportFormat = "csv" | "json";
export interface ImportResult {
imported: number;
errors: number;
errorDetails?: string[];
}
模式:
- 聯合型別(字串字面量)使用
type - 結果物件使用
interface - 包含成功/錯誤追蹤的計數
- 包含可選的錯誤詳細資訊陣列
型別命名慣例
介面
- PascalCase:
User、Task、ApiResponse - 描述性名稱:
TaskFormData、UserSignupData
型別(聯合型別)
- PascalCase:
TaskStatus、TaskPriority、LoadingState - 描述性名稱:
ToastType、ExportFormat
Props 型別
- ComponentName + Props:
TaskItemProps、ProtectedRouteProps - 範例:
interface TaskItemProps { task: Task; }
表單資料型別
- EntityName + FormData:
TaskFormData、UserSignupData - 範例:
interface TaskFormData { title: string; description?: string; }
查詢參數型別
- EntityName + QueryParams:
TaskQueryParams - 範例:
interface TaskQueryParams { status?: "all" | "pending" | "completed"; }
匹配後端結構
欄位名稱對應
後端(蛇形命名法) → 前端(表單資料使用駝峰命名法,API 回應使用蛇形命名法)
// 後端 API 回應(完全匹配後端)
export interface Task {
id: number;
user_id: string; // 來自後端的蛇形命名法
title: string;
due_date?: string; // 來自後端的蛇形命名法
created_at: string; // 來自後端的蛇形命名法
updated_at: string; // 來自後端的蛇形命名法
}
// 前端表單資料(為便於使用使用駝峰命名法)
export interface TaskFormData {
title: string;
dueDate?: string; // 前端的駝峰命名法
tags?: string[];
}
模式:
- API 回應型別完全匹配後端(蛇形命名法)
- 表單資料型別使用駝峰命名法以方便前端使用
- 在發送/接收 API 時進行格式轉換
必要與可選欄位
// 後端 API 回應(所有來自後端的欄位)
export interface Task {
id: number; // 必要(來自後端)
user_id: string; // 必要(來自後端)
title: string; // 必要(來自後端)
description?: string; // 可選(來自後端)
completed: boolean; // 必要(來自後端)
priority: TaskPriority; // 必要(來自後端)
due_date?: string; // 可選(來自後端)
tags: string[]; // 必要(來自後端,可為空陣列)
created_at: string; // 必要(來自後端)
updated_at: string; // 必要(來自後端)
}
// 前端表單資料(僅使用者可編輯的欄位)
export interface TaskFormData {
title: string; // 必要(使用者必須提供)
description?: string; // 可選
priority?: TaskPriority; // 可選(有預設值)
due_date?: string; // 可選
tags?: string[]; // 可選(可為空陣列)
}
模式:
- API 回應型別包含後端的所有欄位
- 表單資料型別僅包含使用者可編輯的欄位
- 可選欄位標記
? - 必要欄位不標記
?
型別結構模式
1. 物件使用 interface
export interface User {
id: string;
email: string;
}
使用時機:具有屬性的物件型別
2. 聯合、交集或別名使用 type
export type TaskStatus = "pending" | "completed";
export type TaskPriority = "low" | "medium" | "high";
使用時機:聯合型別、交集或型別別名
3. 可重用結構使用泛型
export interface ApiResponse<T = unknown> {
data?: T;
success: boolean;
}
使用時機:可與不同型別搭配使用的可重用結構
4. 可選屬性標記 ?
export interface Task {
title: string; // 必要
description?: string; // 可選
}
使用時機:可能不存在的欄位
完整範例:新增型別
步驟 1:定義實體型別(匹配後端)
export interface Category {
id: number;
user_id: string;
name: string;
color?: string;
created_at: string;
updated_at: string;
}
步驟 2:定義表單資料型別(用於使用者輸入)
export interface CategoryFormData {
name: string;
color?: string;
}
步驟 3:定義查詢參數型別(用於 API 查詢)
export interface CategoryQueryParams {
search?: string;
page?: number;
limit?: number;
}
步驟 4:在 API 客戶端中使用
async getCategories(
userId: string,
queryParams?: CategoryQueryParams
): Promise<ApiResponse<PaginatedResponse<Category>>> {
// 實作
}
規範要求
- FR-030:所有 API 呼叫的已輸入 TypeScript 介面 ✅
- FR-037:TypeScript 嚴格模式 ✅
參考資料
- 規格:
specs/002-frontend-todo-app/spec.md- 實體定義 - 計畫:
specs/002-frontend-todo-app/plan.md- 帶有型別的 API 合約 - 型別檔案:
frontend/types/index.ts- 完整的型別定義
常見模式摘要
- ✅ 物件型別使用
interface - ✅ 聯合型別(字串字面量)使用
type - ✅ 可重用結構使用泛型
<T> - ✅ 可選欄位標記
? - ✅ 匹配後端欄位名稱(API 回應使用蛇形命名法)
- ✅ 表單資料型別使用駝峰命名法
- ✅ 為表單資料和查詢參數建立獨立的型別
- ✅ 使用描述性名稱(EntityFormData、EntityQueryParams)
- ✅ 包含後端的所有必要欄位
- ✅ 為泛型提供預設型別參數(
<T = unknown>)