昨天我先學了 TypeScript 的基本型別和 interface,今天要繼續進階:
這些概念在設計 API 的時候很常用,可以讓程式碼更有結構、更安全。
在 JavaScript 裡,我們常用字串來表示狀態,例如 Todo 的狀態:
let status = "done"; // 也可能是 "pending"
但問題是,字串容易打錯,例如 "dnne"
,程式不會報錯。
enum TodoStatus {
Pending, // 預設是 0
InProgress, // 1
Done // 2
}
let status: TodoStatus = TodoStatus.Pending;
console.log(status); // 0
enum TodoStatus {
Pending = "PENDING",
InProgress = "IN_PROGRESS",
Done = "DONE"
}
let status: TodoStatus = TodoStatus.Done;
console.log(status); // "DONE"
這樣就能確保只能使用這幾個狀態,不會亂打字串。
TypeScript 不只幫變數加型別,函式也能加上型別,讓輸入與輸出都受保護。
function add(a: number, b: number): number {
return a + b;
}
a: number
、b: number
→ 限制參數型別: number
→ 限制回傳值型別也可以用 type
或 interface
來定義「函式型別」。
type MathFunc = (a: number, b: number) => number;
const add: MathFunc = (x, y) => x + y;
const sub: MathFunc = (x, y) => x - y;
console.log(add(5, 3)); // 8
console.log(sub(5, 3)); // 2
這樣做的好處是:如果很多函式都用到相同的簽名,就能共用一個型別定義。
我把昨天的 Student
改成 Todo
,結合 Enum 和函式型別:
enum TodoStatus {
Pending = "PENDING",
InProgress = "IN_PROGRESS",
Done = "DONE"
}
interface Todo {
id: number;
task: string;
status: TodoStatus;
}
// 定義一個函式型別
type FilterFunc = (todos: Todo[], status: TodoStatus) => Todo[];
// 實作函式:過濾 Todo
const filterTodos: FilterFunc = (todos, status) => {
return todos.filter(todo => todo.status === status);
};
// 測試
let todos: Todo[] = [
{ id: 1, task: "學 TypeScript", status: TodoStatus.Pending },
{ id: 2, task: "寫鐵人賽文章", status: TodoStatus.InProgress },
{ id: 3, task: "整理筆記", status: TodoStatus.Done }
];
console.log(filterTodos(todos, TodoStatus.Pending));
輸出:
[
{ "id": 1, "task": "學 TypeScript", "status": "PENDING" }
]
今天感受到 TypeScript 的好處:
filterTodos
的時候,VSCode 還會幫我自動提示 Enum 的值,超貼心 ✨對比純 JS,TypeScript 真的讓程式更「嚴謹」,不會亂來。