ข้ามไปเนื้อหาหลัก

TypeScript satisfies — validate type โดยไม่ทำให้ type กว้างขึ้น

satisfies ตรวจว่า value ตรงกับ type ไหม โดยยังเก็บ inferred type ที่แคบกว่าไว้ใช้งาน — ต่างจาก as ที่ยอมทุกอย่าง และ : ที่ทำให้ type กว้างขึ้น

ปัญหาเมื่อ annotate type ตรงๆ:

type Config = Record<string, string | number>;

const config: Config = { host: 'localhost', port: 3000 };
config.port.toFixed(2); // ❌ Error: string | number ไม่มี toFixed

satisfies แก้ได้ — validate ว่า conform กับ type แต่ยัง infer ค่าจริง:

const config = {
  host: 'localhost',
  port: 3000,
} satisfies Config;

config.port.toFixed(2); // ✅ TypeScript รู้ว่า port เป็น number จริงๆ
config.missing;          // ❌ Error: property ไม่มีใน object — ยัง validate อยู่

ใช้ satisfies แทน : Type เมื่อต้องการ:

  1. ตรวจว่า object ครบ shape ที่กำหนด
  2. แต่ยังเข้าถึง property แบบ narrow type ได้