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

as const ทำให้ TypeScript รู้ว่าค่าคือ literal จริงๆ

ไม่ต้อง enum — as const ทำให้ array หรือ object เป็น readonly literal type ที่ infer ได้แม่นยำ

ปัญหาที่เจอบ่อย: เขียน array แล้ว TypeScript infer เป็น string[] แทนที่จะเป็น union literal

const SIZES = ['sm', 'md', 'lg']; // type: string[]
type Size = typeof SIZES[number];  // type: string ❌

เพิ่ม as const แก้ได้ทันที:

const SIZES = ['sm', 'md', 'lg'] as const; // type: readonly ['sm', 'md', 'lg']
type Size = typeof SIZES[number];           // type: 'sm' | 'md' | 'lg' ✅

ใช้กับ object ก็ได้ — ทุก value กลายเป็น literal และ readonly ทั้งหมด เหมาะสำหรับทำ lookup table หรือ config object ที่ต้องการ type safety โดยไม่ต้องใช้ enum

const STATUS = {
  active: 'active',
  done: 'completed',
  archived: 'archived',
} as const;

type Status = typeof STATUS[keyof typeof STATUS]; // 'active' | 'completed' | 'archived'