TypeScript conditional types



conditional type = if-else ในระดับ type

รูปแบบ T extends U ? X : Y

type IsString<T> = T extends string ? true : false;

type A = IsString<string>;    // true
type B = IsString<number>;    // false
type C = IsString<"hello">;   // true  ("hello" extends string)

T extends U = “T assignable กับ U ไหม” — ใช่ → X, ไม่ใช่ → Y

ตัวอย่างใช้จริง

type NonNullable<T> = T extends null | undefined ? never : T;

type A = NonNullable<string | null>;        // string
type B = NonNullable<number | undefined>;   // number

// unwrap array
type ElementType<T> = T extends (infer E)[] ? E : T;

type X = ElementType<string[]>;    // string
type Y = ElementType<number>;      // number  (ไม่ใช่ array → คืน T เดิม)

// flatten one level
type Flatten<T> = T extends Array<infer Item> ? Item : T;

infer — จับ type ออกมา

infer X = “ให้ TS หา type ที่ตำแหน่งนี้ แล้วเรียกมันว่า X”:

// ดึง return type ของฟังก์ชัน
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

type A = MyReturnType<() => string>;              // string
type B = MyReturnType<(x: number) => number[]>;   // number[]

// ดึง type ของ argument แรก
type FirstArg<T> = T extends (first: infer F, ...rest: any[]) => any ? F : never;

type C = FirstArg<(name: string, age: number) => void>;   // string

// unwrap Promise
type Unwrap<T> = T extends Promise<infer V> ? V : T;

type D = Unwrap<Promise<User>>;    // User
type E = Unwrap<string>;           // string

// unwrap หลายชั้น (recursive)
type DeepUnwrap<T> = T extends Promise<infer V> ? DeepUnwrap<V> : T;
type F = DeepUnwrap<Promise<Promise<number>>>;   // number

distributive conditional type

เมื่อ T เป็น union และ T ปรากฏ “เปล่า ๆ” ก่อน extends — conditional กระจายทำงานทีละ member:

type ToArray<T> = T extends any ? T[] : never;

type Result = ToArray<string | number>;
// = ToArray<string> | ToArray<number>
// = string[] | number[]      (ไม่ใช่ (string | number)[]!)
// กรอง union
type Exclude<T, U> = T extends U ? never : T;

type A = Exclude<"a" | "b" | "c", "b">;   // "a" | "c"
// = (("a" extends "b" ? never : "a") | ("b" extends "b" ? never : "b") | ...)
// = "a" | never | "c" = "a" | "c"

type Extract<T, U> = T extends U ? T : never;
type B = Extract<string | number | boolean, string | number>;   // string | number

ปิด distribution ด้วยการครอบ []:

type ToArrayNonDist<T> = [T] extends [any] ? T[] : never;
type R = ToArrayNonDist<string | number>;   // (string | number)[]

สร้าง utility type เอง

// เอาเฉพาะ key ที่ value เป็น type ที่กำหนด
type KeysOfType<T, V> = {
  [K in keyof T]: T[K] extends V ? K : never;
}[keyof T];

interface Form {
  name: string;
  age: number;
  email: string;
  subscribe: boolean;
}

type StringKeys = KeysOfType<Form, string>;   // "name" | "email"
type BoolKeys = KeysOfType<Form, boolean>;    // "subscribe"

// make specific keys optional
type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;

type User = { id: string; name: string; bio: string };
type UserUpdate = PartialBy<User, "name" | "bio">;
// { id: string; name?: string; bio?: string }

nested conditional

type TypeName<T> =
  T extends string ? "string" :
  T extends number ? "number" :
  T extends boolean ? "boolean" :
  T extends undefined ? "undefined" :
  T extends Function ? "function" :
  "object";

type A = TypeName<string>;      // "string"
type B = TypeName<() => void>;  // "function"
type C = TypeName<string[]>;    // "object"

เมื่อไรใช้ conditional type

  • สร้าง utility type ที่ยังไม่มีในตัว
  • library ที่ต้องการ type inference ฉลาด ๆ (return type ขึ้นกับ argument)
  • transform type ตามเงื่อนไข

อย่าใช้เกินจำเป็น — conditional type ซ้อนลึกอ่านยากมาก และ compile ช้า ถ้าเขียน type ตรง ๆ ได้ให้เขียนตรง ๆ

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

  • distribution ทำงานโดยไม่คาด — ToArray<string | number> ได้ string[] | number[]; ครอบ [T] เพื่อปิด
  • infer นอก conditional type — ใช้ได้เฉพาะใน extends clause ของ conditional
  • conditional type ที่ compile ช้ามาก — recursive ลึก / union ใหญ่; หลีกเลี่ยงหรือ simplify
  • T extends any ? ... : ... — any ผ่าน conditional ทั้งสองทาง (เป็น X | Y) ในบางกรณี
  • ลืมว่า T extends U เช็ค assignability ไม่ใช่ equality — IsString<"a"> เป็น true ("a" extends string)
  • nested conditional ไม่มี fallback — ต้องมี : never หรือ default สุดท้าย

สรุป

  • conditional type T extends U ? X : Y — if-else ระดับ type (เช็ค assignability)
  • infer X — จับ type ที่ตำแหน่งใน pattern (ReturnType, unwrap Promise/array)
  • distributive — union ที่ปรากฏเปล่า ๆ ก่อน extends → กระจายทีละ member (Exclude, Extract ใช้); ครอบ [T] เพื่อปิด
  • combo mapped + conditional: { [K in keyof T]: T[K] extends V ? K : never }[keyof T] — กรอง key
  • ใช้สร้าง utility type ที่ไม่มีในตัว — อย่าซ้อนลึกเกินจำเป็น (อ่านยาก, compile ช้า)

บทถัดไปว่าด้วย utility types ในตัว — Partial, Pick, Omit, Record, ReturnType และเพื่อน ๆ