Dark mode
Advanced Types ( type ขั้นสูง)
Recursive Types ( type เรียกซ้ำ)
type ที่สามารถอ้างอิงตัวเองได้ เหมาะสำหรับโครงสร้างข้อมูลแบบ recursive
ts
type Json =
| string
| number
| boolean
| null
| { [key: string]: Json }
| Json[];
const data: Json = {
name: "John",
scores: [90, 85, 95],
metadata: {
active: true,
nested: { id: 1 },
},
};
Template Literal Types ( type เทมเพลตสตริง)
ใช้สร้าง type จากเทมเพลตสตริง
ts
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
type ApiEndpoint = `/api/${string}`;
type ApiRoute = `${HttpMethod} ${ApiEndpoint}`;
const route: ApiRoute = "GET /api/users";
// const invalidRoute: ApiRoute = 'PATCH /api/users'; // Error
Type Inference Deep Dive (การอนุมาน type เชิงลึก)
TypeScript สามารถอนุมาน type ได้จากบริบทต่างๆ
ts
// อนุมานจากค่าเริ่มต้น
let score = 100; // TypeScript รู้ว่าเป็น number
// อนุมานจาก return type
function add(a: number, b: number) {
return a + b; // อนุมานว่า return เป็น number
}
// อนุมานจาก array
const tuples = [
["John", 30], // อนุมานเป็น (string | number)[]
["Jane", 25],
] as const; // อนุมานเป็น readonly ["John", 30] | readonly ["Jane", 25]
หมายเหตุ:
- ใช้
as const
สำหรับ literal type inference - ใช้ generic constraints สำหรับการอนุมานที่ซับซ้อน
- ระวังการอนุมาน type ที่กว้างเกินไป