執行 TypeScript 類型檢查並修復類型錯誤。當遇到類型錯誤、需要類型定義、或用戶提到「type」、「類型」時使用。
專門處理 TypeScript 類型檢查和類型錯誤修復。
npm run typecheck 發現錯誤any 需要替換為具體類型npm run typecheck
TypeScript 錯誤格式:
src/components/Login.tsx:42:15 - error TS7006: Parameter 'user' implicitly has an 'any' type.
需要提取:
src/components/Login.tsx42TS7006Parameter 'user' implicitly has an 'any' type必須閱讀的檔案(按順序):
# 搜尋類型定義檔案
Glob: pattern="**/types/**/*.ts"
Glob: pattern="**/*.d.ts"
# 在檔案中搜尋 interface 定義
Grep: pattern="^(export\\s+)?(interface|type)\\s+" output_mode="content"
// ❌ 錯誤
function handleUser(user: any) {}
// ✅ 使用專案中已定義的類型
import { User } from "@/types/user";
function handleUser(user: User) {}
如果專案中沒有合適的類型,在適當位置定義:
// 在 src/types/[domain].ts 中定義
export interface UserProfile {
id: string;
name: string;
email: string;
role: "admin" | "user" | "guest";
}
// ❌ 錯誤
function fetchData(url: string): Promise<any> {}
// ✅ 使用泛型
function fetchData<T>(url: string): Promise<T> {}
// ❌ 錯誤
const handleClick = (e) => {};
// ✅ 修復
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {};
// ❌ 錯誤
interface User {
name: string;
}
user.email; // Property 'email' does not exist
// ✅ 修復:擴展 interface
interface User {
name: string;
email: string;
}
// ❌ 錯誤
function greet(name: string) {}
greet(123);
// ✅ 修復:確保參數類型正確
greet(String(123));
// 或
greet(userId.toString());
// ❌ 錯誤
const user = users.find((u) => u.id === id);
console.log(user.name); // 'user' is possibly 'undefined'
// ✅ 修復:加入 null check
const user = users.find((u) => u.id === id);
if (user) {
console.log(user.name);
}
// 或使用可選鏈
console.log(user?.name);
// Props 類型
interface ButtonProps {
label: string;
onClick: () => void;
disabled?: boolean;
}
// Event handlers
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {};
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {};
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {};
// State 類型
const [user, setUser] = useState<User | null>(null);
const [items, setItems] = useState<Item[]>([]);
// Ref 類型
const inputRef = useRef<HTMLInputElement>(null);
npm run typecheck 驗證// ❌ 永遠不要這樣做
const data: any = fetchData();
function process(input: any): any {}
// @ts-ignore
const result = riskyOperation();
src/types/ 目錄src/types/[domain].ts## TypeScript 類型修復報告
### 修復的錯誤
1. **src/components/Login.tsx:42**
- 錯誤: TS7006 - Parameter 'user' implicitly has an 'any' type
- 修復: 使用 `User` interface from `@/types/user`
- 狀態: ✅ 已修復
2. **src/api/auth.ts:15**
- 錯誤: TS2345 - Argument type mismatch
- 修復: 調整參數類型為 `LoginCredentials`
- 狀態: ✅ 已修復
### 驗證結果
```bash
npm run typecheck
```
✅ 無類型錯誤
src/types/auth.ts - LoginCredentials, AuthResponse
## 🔗 參考資源
- TypeScript 官方文檔: https://www.typescriptlang.org/docs/
- React TypeScript Cheatsheet: https://react-typescript-cheatsheet.netlify.app/
- 專案規範: `/home/user/maihouses/CLAUDE.md`