Type-Level Programming
type คือภาษาหนึ่ง
หัวข้อที่มีชื่อว่า “type คือภาษาหนึ่ง”ที่ผ่านมา type ทำหน้าที่ อธิบาย ข้อมูล ในโมดูลนี้ type จะเริ่ม คำนวณ จากข้อมูลนั้น จาก type หนึ่งคุณ derive อีก type ออกมาได้ — ทำให้ทุก field เป็น optional, pick key แค่บางส่วน, ดึง return type ของ function ออกมา หรือ parse string ให้เป็น union — ทั้งหมดที่ระดับ type โดย compiler ประเมินก่อน code รัน
นี่คือการเขียนโปรแกรมจริง ๆ type system มีตัวแปร (type parameter), การ branch (conditional type), การวนซ้ำ (mapped type และ recursion) และ function (generic type alias) มีคนเขียน arithmetic หรือแม้แต่ parser ด้วย type ล้วน ๆ คุณคงไม่ทำแบบนั้นในงานจริง — แต่เข้าใจกลไกนี้คือสิ่งที่ทำให้คุณ อ่าน type ของ library ออก และเขียน type เจ๋ง ๆ ไม่กี่ตัวที่คุ้มค่าจริง
โมดูลนี้ครอบคลุมอะไรบ้าง
หัวข้อที่มีชื่อว่า “โมดูลนี้ครอบคลุมอะไรบ้าง”| บทเรียน | สิ่งที่คุณจะได้เรียน |
|---|---|
| Mapped types | วนซ้ำ key ของ type เพื่อ transform แต่ละ property — สร้าง Partial และ Readonly เอง |
| keyof & indexed access | keyof T และ T[K] — การ lookup ที่เป็นฐานของทุกอย่าง |
| Template literal types | คำนวณ string type และ pattern-match string ด้วย infer |
| The utility types | ตัว built-in และวิธีที่ถูก implement จริง |
| Recursive types | type ที่เรียกตัวเอง — และจุดที่ compiler ขีดเส้น |
ชิ้นส่วนต่าง ๆ ประกอบกัน
หัวข้อที่มีชื่อว่า “ชิ้นส่วนต่าง ๆ ประกอบกัน”flowchart TB keyof["keyof T (get the keys)"] --> mapped["Mapped types (iterate the keys)"] indexed["T[K] (look up value types)"] --> mapped cond["Conditional types + infer (branch and capture)"] --> util["Utility types (Pick, Exclude, ReturnType)"] mapped --> util tmpl["Template literals (compute strings)"] --> util util --> rec["Recursion (repeat until done)"]
แทบทุก type ขั้นสูงในโลกจริงคือการผสม 5 primitive: keyof เพื่อเอา key, indexed access เพื่อ lookup value type, mapped type เพื่อวนซ้ำ, conditional type กับ infer เพื่อ branch และ capture, และ recursion เพื่อทำซ้ำ เรียน 5 ตัวนี้แล้วไฟล์ .d.ts ของ library จะเลิกเป็นอักษรอียิปต์โบราณ