Week 02 · Day 03 — TypeScript 函式
學習目標
- 學會為函式的參數與回傳值加上型別
- 認識回傳
void的函式 - 建立帶型別參數的函式
重點
基本函式(帶型別)
function add(a: number, b: number): number {
return a + b;
}
a: number
- 回傳型別寫在 ): number,若無回傳用 : void
回傳 void
function log(message: string): void {
console.log(message);
// 沒有 return 或 return;(不回傳值)
}
參數缺一不可 - TS 預設所有參數皆「必要」
add(1); // ❌ 編譯錯誤:缺少第二個參數
add("a", 1); // ❌ 型別不符
add(1, 2); // ✅
表面型別 vs 回傳值:回傳型別不符也會報錯
function bad(): number {
return "hello"; // ❌ 型別錯誤
}
實作
function calculateTotal(price: number, quantity: number): number {
return price * quantity;
}
function printTotal(total: number): void {
console.log(`Total: ${total}`);
}
const total = calculateTotal(120, 3);
printTotal(total); // Total: 360
作業
- 建立一個回傳
number的函式(如計算總價) - 建立一個回傳
void的函式(如列印訊息) - 說出
: number與: void分別代表什麼