ข้ามไปยังเนื้อหา

Everyday Types, Deep

คุณหยิบพวกนี้มาใช้ทุกวัน: string literal, union, object shape, tuple, function โมดูลนี้จะค่อย ๆ เจาะจุดที่คนมักสะดุด — widening, as const, ความต่างระหว่าง union กับ intersection และ control-flow narrowing ที่ทำให้ union ใช้งานได้จริง

ทุกอย่างในนี้ตั้งอยู่บน model จาก Foundations: type คือเซตของ value ถือ lens นี้ไว้ แล้วแต่ละ feature ก็แค่วิธีอธิบายหรือย่อเซตให้เล็กลง

บทเรียนสิ่งที่คุณจะได้เรียนรู้
Literals & wideningliteral type, จะ widen เมื่อไร และ as const
Unions & intersectionsA | B (กว้างกว่า) เทียบ A & B (แคบกว่า) และวิธีทำงานกับแต่ละแบบ
Objects, arrays & tuplesproperty แบบ optional/readonly, index signature, tuple
Functionsoverload, this typing, rest param, ประเด็น void
Narrowingเปลี่ยน union ให้เป็น type เฉพาะด้วย control flow
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"]
everyday typing คือ describe แล้ว narrow

คุณ describe ข้อมูลด้วย union และ object type ซึ่งทำให้คุณถือ type ที่ กว้าง อยู่ (มีหลายความเป็นไปได้) จากนั้นก็ narrow — ด้วย typeof, in, discriminant field — ลงมาเหลือ case เฉพาะตัวเดียว แล้ว TypeScript ก็ยอมให้ใช้งานอย่างปลอดภัย เข้าใจ loop นี้แล้วคุณก็เข้าใจ TypeScript ในชีวิตประจำวัน

จังหวะที่เกิดซ้ำ ๆ ของ TypeScript ในชีวิตประจำวันคืออะไร?
model พื้นฐานอันไหนที่ร้อยโมดูลนี้เข้าด้วยกัน?