TypeScript generics และ type ขั้นสูง



template literal types

สร้าง string literal type จาก pattern:

type Greeting = `Hello, ${string}!`;
const g: Greeting = "Hello, World!";     // OK
const bad: Greeting = "Hi";              // Error

type Route = `/api/${string}`;
type CssSize = `${number}px` | `${number}rem` | `${number}%`;

// combination — Cartesian product
type Position = "top" | "bottom";
type Alignment = "left" | "center" | "right";
type Placement = `${Position}-${Alignment}`;
// "top-left" | "top-center" | "top-right" | "bottom-left" | ...

template literal + mapped type — event handlers

type EventMap = {
  click: MouseEvent;
  focus: FocusEvent;
  keydown: KeyboardEvent;
};

type Handlers = {
  [K in keyof EventMap as `on${Capitalize<K>}`]?: (event: EventMap[K]) => void;
};
// { onClick?: (e: MouseEvent) => void; onFocus?: ...; onKeydown?: ... }

template literal + infer — parse string type

type ExtractParams<T extends string> =
  T extends `${string}:${infer Param}/${infer Rest}`
    ? Param | ExtractParams<`/${Rest}`>
    : T extends `${string}:${infer Param}`
      ? Param
      : never;

type Params = ExtractParams<"/users/:userId/posts/:postId">;
// "userId" | "postId"

typed route params, typed template strings — library อย่าง Hono, Elysia ใช้เทคนิคนี้

const type parameter (TS 5.0)

// ❌ ก่อน 5.0 — ต้อง as const
function makeTuple<T>(items: T[]): T[] {
  return items;
}
const a = makeTuple(["a", "b"]);           // string[]
const b = makeTuple(["a", "b"] as const);  // readonly ["a", "b"]

// ✅ TS 5.0 — const modifier
function makeTuple2<const T>(items: T[]): T[] {
  return items;
}
const c = makeTuple2(["a", "b"]);          // readonly ["a", "b"]  — ไม่ต้อง as const!

<const T> — infer T เป็น literal/tuple เหมือน caller เขียน as const

function defineRoutes<const T extends Record<string, string>>(routes: T): T {
  return routes;
}

const routes = defineRoutes({
  home: "/",
  about: "/about",
});
// { readonly home: "/"; readonly about: "/about" }
routes.home;   // "/"

recursive types

// JSON value
type JsonValue =
  | string
  | number
  | boolean
  | null
  | JsonValue[]
  | { [key: string]: JsonValue };

// tree
interface TreeNode<T> {
  value: T;
  children: TreeNode<T>[];
}

// deep readonly
type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
};

// path type (nested key access)
type NestedKeyOf<T> = {
  [K in keyof T & string]: T[K] extends object
    ? `${K}` | `${K}.${NestedKeyOf<T[K]>}`
    : `${K}`;
}[keyof T & string];

type UserKeys = NestedKeyOf<{
  name: string;
  address: { city: string; zip: string };
}>;
// "name" | "address" | "address.city" | "address.zip"

recursive type ลึกเกิน ~50 ชั้น → TS ยอมแพ้ (Type instantiation is excessively deep)

NoInfer (TS 5.4)

ควบคุมว่าไม่ให้ infer T จากตำแหน่งนี้:

function createState<T>(initial: T, defaultValue: NoInfer<T>): T {
  return initial ?? defaultValue;
}

// ❌ ก่อน NoInfer — T infer จากทั้ง 2 ตำแหน่ง → union
// createState("red", "blue")  → T = "red" | "blue"

// ✅ NoInfer — T infer จาก initial เท่านั้น
createState<"red" | "green" | "blue">("red", "green");   // ต้องเป็น literal ที่กำหนด
createState("red", "purple");   // Error ถ้ามี constraint

variance (เข้าใจพอสังเขป)

  • covariant — Dog[] assign ให้ Animal[] ได้ (subtype → supertype)
  • contravariant — (a: Animal) => void assign ให้ (a: Dog) => void ได้ (function parameter กลับทิศ)
type Animal = { name: string };
type Dog = Animal & { breed: string };

let animals: Animal[] = [];
let dogs: Dog[] = [{ name: "โฮ่ง", breed: "x" }];
animals = dogs;   // OK — covariant (แต่ไม่ sound: animals.push({name}) แล้ว dogs มี non-Dog)

// strictFunctionTypes บังคับ contravariance ของ function parameter

TS 4.7+ ให้ระบุ variance ชัด: interface Box<out T> / <in T> (นาน ๆ ใช้)

branded types (nominal — ทบทวนบทที่ 19)

type Brand<T, B extends string> = T & { readonly __brand: B };

type UserId = Brand<string, "UserId">;
type PostId = Brand<string, "PostId">;

function getUser(id: UserId) { }

const uid = "u1" as UserId;
const pid = "p1" as PostId;
getUser(uid);   // OK
getUser(pid);   // Error — PostId ไม่ใช่ UserId
getUser("u1");  // Error — string ธรรมดาไม่ใช่ UserId

เมื่อไรหยุด

type ขั้นสูงเหล่านี้ทรงพลังแต่:

  • อ่านยาก — คนในทีมต้องเข้าใจ
  • compile ช้า — recursive/conditional ลึก
  • error message งง — เมื่อ type ไม่ตรง

ใช้เมื่อ library / infrastructure ที่ทำครั้งเดียวใช้หลายที่ — โค้ด application ทั่วไปแทบไม่ต้อง

เรื่องที่คนมักพลาด

  • recursive type ลึกเกิน — Type instantiation is excessively deep; จำกัด depth หรือ simplify
  • template literal ${number} แล้วคาดว่ารับ number — รับ `${number}` (string ที่เป็นตัวเลข)
  • <const T> ทุก generic — เกินจำเป็น; ใช้เมื่ออยากได้ literal โดยไม่ให้ caller เขียน as const
  • branded type แล้วลืมว่า as bypass ได้ — brand ช่วยเรื่อง accidental mixing ไม่ใช่ security
  • conditional/mapped type ซ้อนลึกในโค้ด app — magic; เขียน type ตรง ๆ ถ้าทำได้

สรุป

  • template literal types — `${A}-${B}` สร้าง string type จาก pattern; + mapped type (on${Capitalize<K>}); + infer (parse route params)
  • <const T> (TS 5.0) — infer T เป็น literal/tuple เหมือน as const (ไม่ต้องให้ caller เขียน)
  • recursive types — JSON value, tree, DeepReadonly, NestedKeyOf (ลึกเกิน ~50 → error)
  • NoInfer<T> (5.4) — ไม่ให้ infer T จากตำแหน่งนั้น
  • variance — array covariant, function param contravariant (strictFunctionTypes)
  • branded types — T & { __brand: "X" } = nominal (ป้องกัน accidental mixing)
  • ใช้กับ library/infra เท่านั้น — โค้ด app ทั่วไปไม่ต้อง

จบเฟสเครื่องมือ บทถัดไปเข้าเฟสเฟรมเวิร์ก เริ่มที่ TypeScript กับ React