Skip to content

Basic Types ใน TypeScript

TypeScript มี type พื้นฐานที่ครอบคลุมทุกรูปแบบข้อมูลที่ใช้ในการพัฒนา

// Type Annotations — ระบุ type ชัดเจน
let username: string = "สมชาย";
let age: number = 25;
let isActive: boolean = true;
// Type Inference — TS เดา type ให้อัตโนมัติ
let city = "กรุงเทพ"; // inferred as string
let score = 95.5; // inferred as number
let enrolled = false; // inferred as boolean
// 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 enum
enum Role {
Admin, // 0
Editor, // 1
Viewer // 2
}
// String enum — แนะนำสำหรับ readability
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
Pending = "PENDING"
}
let userRole: Role = Role.Admin;
let userStatus: Status = Status.Active;
// 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);
}
// 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 ได้ถ้าชัดเจน