คุณกำหนด type ให้กับ parameter และค่าที่คืนกลับ และ TypeScript รองรับ optional, default และ rest parameter
ts
(): { a + b; }
(): {
title ? : name;
}
(): { n + by; }
(): {
nums.( a + n, );
}
คุณกำหนด type ให้กับ parameter และค่าที่คืนกลับ และ TypeScript รองรับ optional, default และ rest parameter
(): { a + b; }
(): {
title ? : name;
}
(): { n + by; }
(): {
nums.( a + n, );
}
คุณสามารถอธิบาย signature ของฟังก์ชันให้เป็น type ได้ ซึ่งมีประโยชน์สำหรับ callback และตัวแปรที่เก็บฟังก์ชันไว้:
type BinaryOp = (a: number, b: number) => number;
const multiply: BinaryOp = (a, b) => a * b; // params inferred from BinaryOp
// callback parameter
function apply(op: (x: number) => number, val: number) { return op(val); }
function parse(x: string): number;
function parse(x: number): string;
function parse(x: any): any { return typeof x === "string" ? +x : String(x); }
การกำหนด type ให้ฟังก์ชันอย่างแม่นยำคือแก่นของคุณค่าที่ TypeScript มอบให้ ผู้เรียกใช้จะได้รับ argument ที่ถูกตรวจสอบและรู้ type ของค่าที่คืนกลับ optional/default param ช่วยจำลองความยืดหยุ่นในโลกจริง และ type alias ของฟังก์ชันทำให้โค้ดลำดับสูง (callback, event handler, middleware) อธิบายตัวเองได้และปลอดภัย