Basic Types ใน TypeScript
Basic Types ใน TypeScript
Section titled “Basic Types ใน TypeScript”TypeScript มี type พื้นฐานที่ครอบคลุมทุกรูปแบบข้อมูลที่ใช้ในการพัฒนา
Primitive Types
Section titled “Primitive Types”// Type Annotations — ระบุ type ชัดเจนlet username: string = "สมชาย";let age: number = 25;let isActive: boolean = true;
// Type Inference — TS เดา type ให้อัตโนมัติlet city = "กรุงเทพ"; // inferred as stringlet score = 95.5; // inferred as numberlet enrolled = false; // inferred as boolean// JS ไม่มี type annotations — ต้อง check ด้วย typeof เองlet username = "สมชาย";let age = 25;console.log(typeof age); // "number"# Python มี type hints แต่ไม่บังคับusername: str = "สมชาย"age: int = 25is_active: bool = True-- SQL กำหนด type ตอนสร้างตารางCREATE TABLE users ( username VARCHAR(100), age INT, is_active BOOLEAN);Array และ Tuple
Section titled “Array และ Tuple”// Array — สองวิธีในการประกาศlet scores: number[] = [90, 85, 78];let names: Array<string> = ["Alice", "Bob"];
// Tuple — array ที่กำหนดจำนวนและ type แต่ละตำแหน่งlet student: [string, number] = ["สมหญิง", 22];let record: [number, string, boolean] = [1, "active", true];// Numeric enumenum Role { Admin, // 0 Editor, // 1 Viewer // 2}
// String enum — แนะนำสำหรับ readabilityenum Status { Active = "ACTIVE", Inactive = "INACTIVE", Pending = "PENDING"}
let userRole: Role = Role.Admin;let userStatus: Status = Status.Active;Special Types: any, unknown, void, never
Section titled “Special Types: any, unknown, void, never”// any — ปิด type checking (หลีกเลี่ยง!)let data: any = "hello";data = 42; // ไม่ error แต่ไม่ปลอดภัย
// unknown — ปลอดภัยกว่า any ต้อง check ก่อนใช้let input: unknown = "hello";if (typeof input === "string") { console.log(input.toUpperCase()); // OK หลัง check}
// void — function ที่ไม่ return ค่าfunction logMessage(msg: string): void { console.log(msg);}
// never — function ที่ไม่มีทาง return (throw error, infinite loop)function throwError(msg: string): never { throw new Error(msg);}Type Annotation vs Type Inference
Section titled “Type Annotation vs Type Inference”// Annotation: ระบุเอง — ใช้เมื่อ TS เดาไม่ได้function add(a: number, b: number): number { return a + b;}
// Inference: TS เดาให้ — ใช้เมื่อชัดเจนอยู่แล้วconst total = add(10, 20); // total: number (inferred)const items = [1, 2, 3]; // items: number[] (inferred)กฎง่ายๆ: ใช้ annotation กับ function parameters เสมอ ส่วน return type และ variables ปล่อยให้ TS infer ได้ถ้าชัดเจน