Dark mode
Conditional Types (ประเภทตามเงื่อนไข)
ช่วยให้เราสามารถเลือกประเภทตามเงื่อนไขได้ โดยมีรูปแบบพื้นฐานคือ T extends U ? X : Y
Basic Syntax (ไวยากรณ์พื้นฐาน)
ts
// @errors: 2304
type Example<T, U, X, Y> = T extends U ? X : Y;
Type Inference (การอนุมานประเภท)
การใช้ infer
ช่วยให้เราสามารถดึง type ออกจาก conditional type ได้ โดย TypeScript จะทำการ infer type ให้อัตโนมัติ TypeScript สามารถ infer type ใน conditional types ได้:
ts
type GetReturnType<T> = T extends (...args: never[]) => infer R ? R : never;
Distributive Behavior (พฤติกรรมการกระจาย)
เมื่อใช้ conditional type กับ union type มันจะกระจายการทำงานไปยังแต่ละ member ของ union แยกกัน Conditional types จะกระจายไปยัง union types:
ts
type ToArray<T> = T extends any ? T[] : never;
type StrOrNumArr = ToArray<string | number>; // string[] | number[]
Built-in Conditional Types (ประเภทตามเงื่อนไขที่มีในตัว)
Exclude (การคัดออก)
ใช้สำหรับกรอง type ที่ไม่ต้องการออกจาก union type
ts
type Exclude<T, U> = T extends U ? never : T;
Extract (การคัดเลือก)
ใช้สำหรับเลือกเฉพาะ type ที่ต้องการจาก union type
ts
type Extract<T, U> = T extends U ? T : never;
NonNullable (ไม่เป็นค่า null)
ใช้สำหรับกรองค่า null และ undefined ออกจาก type
ts
type NonNullable<T> = T extends null | undefined ? never : T;
ReturnType (ประเภทที่ส่งคืน)
ts
type ReturnType<T> = T extends (...args: never[]) => infer R ? R : never;