TypeScript ฟังก์ชัน



type ของพารามิเตอร์และ return

function add(a: number, b: number): number {
  return a + b;
}

// return type มัก infer ได้ — ไม่ต้องเขียน
function multiply(a: number, b: number) {
  return a * b;              // TS infer return เป็น number
}

const greet = (name: string): string => `สวัสดี ${name}`;

เขียน type ให้พารามิเตอร์เสมอ (TS infer ไม่ได้ ยกเว้น callback ที่มี context) return type ปล่อยให้ infer เว้นแต่อยากบังคับหรือเป็น public API

optional parameter — ?

function greet(name: string, greeting?: string): string {
  return `${greeting ?? "สวัสดี"} ${name}`;
}

greet("อร");                 // "สวัสดี อร"
greet("อร", "ยินดีต้อนรับ");  // "ยินดีต้อนรับ อร"

greeting?: string = greeting: string | undefined — optional param ต้องอยู่หลัง required param

default value

function greet(name: string, greeting = "สวัสดี"): string {
  return `${greeting} ${name}`;   // greeting: string (infer จาก default)
}

param ที่มี default = optional โดยปริยาย — ไม่ต้องใส่ ?

rest parameter

function sum(...nums: number[]): number {
  return nums.reduce((acc, n) => acc + n, 0);
}

sum(1, 2, 3);            // 6
sum(10, 20, 30, 40);    // 100

const values = [1, 2, 3];
sum(...values);         // spread

// rest ที่เป็น tuple — บังคับ argument
function createUser(...args: [name: string, age: number, active?: boolean]) {
  const [name, age, active = true] = args;
}

function type

type BinaryOp = (a: number, b: number) => number;

const add: BinaryOp = (a, b) => a + b;      // a, b infer เป็น number จาก BinaryOp
const sub: BinaryOp = (a, b) => a - b;

function calculate(a: number, b: number, op: BinaryOp): number {
  return op(a, b);
}

calculate(10, 3, add);      // 13
calculate(10, 3, (x, y) => x * y);   // 30

หรือเขียนใน interface (call signature):

interface Formatter {
  (value: number): string;
  precision: number;         // function ที่มี property
}

void — ไม่คืนค่า

function log(message: string): void {
  console.log(message);
}

// callback ที่ประกาศ void — ผู้ implement คืนค่าอะไรก็ได้ (TS ละเลย)
const nums = [1, 2, 3];
nums.forEach((n) => n * 2);   // OK — arrow คืน number แต่ forEach รับ (n) => void

() => void ในตำแหน่ง callback = “ฉันไม่สนค่าที่คืน” — ต่างจาก return type void ที่แปลว่า “ฟังก์ชันนี้ไม่คืนอะไร”

callback types

function repeat(n: number, callback: (index: number) => void): void {
  for (let i = 0; i < n; i++) {
    callback(i);
  }
}

repeat(3, (i) => console.log(`รอบที่ ${i}`));   // i: number infer จาก signature

contextual typing — TS infer type ของพารามิเตอร์ callback จาก signature ที่ประกาศ ทำให้ไม่ต้องเขียน (i: number)

function overloads

ฟังก์ชันที่รับหลายรูปแบบ argument และ return type ต่างกันตาม:

// overload signatures
function parseInput(input: string): string[];
function parseInput(input: number): number;
// implementation signature (ไม่ถูกเรียกตรง ๆ — ต้องครอบทุก overload)
function parseInput(input: string | number): string[] | number {
  if (typeof input === "string") {
    return input.split(",");
  }
  return input * 2;
}

const a = parseInput("a,b,c");   // string[]
const b = parseInput(21);        // number
const c = parseInput(true);      // Error: ไม่มี overload ที่รับ boolean

ส่วนใหญ่ union type + narrowing ทำได้ดีกว่า overload — ใช้ overload เมื่อความสัมพันธ์ input↔output ซับซ้อนจน union ทำไม่ได้

this parameter

interface Button {
  label: string;
  onClick(this: Button, event: Event): void;
}

// this เป็นพารามิเตอร์แรก (fake) — TS ตรวจว่าเรียกด้วย this ที่ถูก type, JS ไม่เห็น

generic function (เกริ่น — บทที่ 11)

function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

first([1, 2, 3]);        // number | undefined
first(["a", "b"]);       // string | undefined

เรื่องที่คนมักพลาด

  • ไม่ใส่ type ให้พารามิเตอร์ — ได้ implicit any (noImplicitAny เตือน); ต้องเขียน (a: number)
  • เขียน return type เมื่อไม่จำเป็น — ปล่อยให้ infer (ยกเว้น public API / recursive / อยากบังคับ)
  • optional param ก่อน required — function f(a?: string, b: number) — error
  • สับสน void return type กับ () => void callback — callback รับค่าคืนอะไรก็ได้ (ละเลย)
  • ใช้ overload ทั้งที่ union พอ — union + typeof narrow อ่านง่ายกว่า
  • Function type — รับ function อะไรก็ได้ (ไม่ปลอดภัย); ใช้ (args) => ReturnType เจาะจง
  • callback param ที่ต้องเขียน type เอง — ถ้า signature ประกาศไว้แล้ว TS infer ให้ (contextual typing)

สรุป

  • ใส่ type ให้พารามิเตอร์เสมอ, return type ปล่อยให้ infer (เว้น public API)
  • param?: T optional (หลัง required), param = default (optional โดยปริยาย), ...rest: T[]
  • type Fn = (a: T) => U — function type; contextual typing infer callback param ให้
  • void return = ไม่คืนค่า; () => void ใน callback = ละเลยค่าคืน
  • overload สำหรับ input↔output ที่ซับซ้อน — แต่ union + narrowing มักดีกว่า
  • <T> generic function — infer T จาก argument

จบเฟส 1 บทถัดไปเข้าเฟส 2 หัวใจของ type system เริ่มที่ union type และ narrowing