Everyday Types, Deep
type ที่คุณใช้อยู่แล้ว — แบบเข้าใจจริง
หัวข้อที่มีชื่อว่า “type ที่คุณใช้อยู่แล้ว — แบบเข้าใจจริง”คุณหยิบพวกนี้มาใช้ทุกวัน: string literal, union, object shape, tuple, function โมดูลนี้จะค่อย ๆ เจาะจุดที่คนมักสะดุด — widening, as const, ความต่างระหว่าง union กับ intersection และ control-flow narrowing ที่ทำให้ union ใช้งานได้จริง
ทุกอย่างในนี้ตั้งอยู่บน model จาก Foundations: type คือเซตของ value ถือ lens นี้ไว้ แล้วแต่ละ feature ก็แค่วิธีอธิบายหรือย่อเซตให้เล็กลง
โมดูลนี้ครอบคลุมอะไรบ้าง
หัวข้อที่มีชื่อว่า “โมดูลนี้ครอบคลุมอะไรบ้าง”| บทเรียน | สิ่งที่คุณจะได้เรียนรู้ |
|---|---|
| Literals & widening | literal type, จะ widen เมื่อไร และ as const |
| Unions & intersections | A | B (กว้างกว่า) เทียบ A & B (แคบกว่า) และวิธีทำงานกับแต่ละแบบ |
| Objects, arrays & tuples | property แบบ optional/readonly, index signature, tuple |
| Functions | overload, this typing, rest param, ประเด็น void |
| Narrowing | เปลี่ยน union ให้เป็น type เฉพาะด้วย control flow |
เส้นเรื่องหลัก: describe แล้วค่อย narrow
หัวข้อที่มีชื่อว่า “เส้นเรื่องหลัก: describe แล้วค่อย narrow”flowchart LR describe["Describe the shape (literals, unions, objects)"] --> hold["Hold a wide type (a union of possibilities)"] hold --> narrow["Narrow with control flow (typeof, in, discriminants)"] narrow --> use["Use the specific type safely"]
คุณ describe ข้อมูลด้วย union และ object type ซึ่งทำให้คุณถือ type ที่ กว้าง อยู่ (มีหลายความเป็นไปได้) จากนั้นก็ narrow — ด้วย typeof, in, discriminant field — ลงมาเหลือ case เฉพาะตัวเดียว แล้ว TypeScript ก็ยอมให้ใช้งานอย่างปลอดภัย เข้าใจ loop นี้แล้วคุณก็เข้าใจ TypeScript ในชีวิตประจำวัน