Back to notes
mastery-frontend-typescript

เจาะลึก Functions ใน TypeScript: เขียนฟังก์ชันให้ Clean และ Type-Safe

เรียนรู้วิธีเขียน Function ใน TypeScript ตั้งแต่พื้นฐานจนถึงเทคนิค Advanced อย่าง Overloads และการจัดการ Parameters แบบมือโปร

January 29, 20262 min read readNNexis by Seereen

Overview

ฟังก์ชัน (Function) คือหัวใจของการเขียนโปรแกรม การเขียนฟังก์ชันที่ดีช่วยให้โค้ดอ่านง่าย เทสง่าย และลดบั๊ก ใน TypeScript เราสามารถเพิ่มพลังให้ฟังก์ชันด้วยการระบุ Type ของ Input และ Output เพื่อความปลอดภัยสูงสุด

Key Ideas

1. Function Declaration Styles

การประกาศฟังก์ชันมีหลายแบบ แต่ที่นิยมที่สุดในปัจจุบันคือ Arrow Function

  • Standard Declaration: มี Hoisting (เรียกก่อนประกาศได้)
  • Arrow Function: สั้นกว่า จัดการ this ได้ดีกว่า (ไม่มี Hoisting)
HLJS TYPESCRIPT
// ✅ Arrow Function (Modern Style)
const add = (a: number, b: number): number => a + b;

// ✅ Standard Declaration (Classic Style)
function addClassic(a: number, b: number): number {
  return a + b;
}

2. Parameters Management

TypeScript ช่วยให้การจัดการ Parameter ยืดหยุ่นและปลอดภัยขึ้น

  • Default Parameters: กำหนดค่าเริ่มต้นกันตาย
  • Optional Parameters (?): ส่งหรือไม่ส่งก็ได้
  • Rest Parameters (...): รับค่าไม่จำกัดจำนวน

3. Void Type

ถ้าฟังก์ชัน "ทำงานอย่างเดียว" แต่ไม่ส่งค่ากลับ เราจะใช้ Type เป็น void (ต่างจาก any นะ! void คือตั้งใจไม่คืนค่า)

Example

HLJS TYPESCRIPT
// 1. Optional & Default Parameters
function createUser(name: string, role: string = "User", age?: number): string {
  const ageInfo = age ? `, Age: ${age}` : "";
  return `Created: ${name} (${role})${ageInfo}`;
}

console.log(createUser("Alice")); // "Created: Alice (User)"
console.log(createUser("Bob", "Admin", 30)); // "Created: Bob (Admin), Age: 30"

// 2. Rest Parameters
const sumAll = (...numbers: number[]): number => {
  return numbers.reduce((total, n) => total + n, 0);
};

console.log(sumAll(1, 2, 3, 4, 5)); // 15

Function Overloads (Advanced)

บางครั้งฟังก์ชันเดียว อาจรับค่าได้หลายรูปแบบ เราใช้ Overload เพื่อบอก TypeScript ให้เข้าใจทุกกรณี

HLJS TYPESCRIPT
// 1. ประกาศ Signature (รูปแบบที่ยอมรับ)
function getPadding(all: number): number;
function getPadding(top: number, left: number): number;

// 2. Implementation (โค้ดจริงต้องรับได้ทุกแบบ)
function getPadding(a: number, b?: number): number {
  if (b === undefined) {
    return a; // กรณีส่งมาตัวเดียว
  }
  return a + b; // กรณีส่งมาสองตัว
}

Pitfalls (สิ่งที่ควรระวัง)

❌ 1. การไม่ระบุ Return Type

ทำไม? แม้ TS จะเดาได้ (Inference) แต่การเขียนกำกับไว้ช่วยให้เรา (และเพื่อนร่วมทีม) รู้ทันทีว่าฟังก์ชันนี้ควรคืนค่าอะไร และช่วยกันเราเขียนผิด (เช่น ลืม return)

❌ 2. ใช้ Optional Parameter ก่อน Required Parameter

ทำไม? Parameter ที่จำเป็นต้องมาก่อนเสมอ

HLJS TYPESCRIPT
// ❌ ผิด
function test(a?: string, b: string) {}

// ✅ ถูก
function test(b: string, a?: string) {}

References

Share this note

© 2026 My Notes by Seereen