TypeScript literal type และ as const



literal type

type ที่เป็น ค่าเดียวเป๊ะ ๆ:

let x: "hello";       // x เก็บได้แค่ "hello" เท่านั้น
x = "hello";          // OK
x = "world";          // Error

let status: 200 | 404 | 500;
let answer: true;

ตัวเดียวไม่มีประโยชน์ — union ของ literal ต่างหากที่ทรงพลัง:

type Direction = "north" | "south" | "east" | "west";
type HttpStatus = 200 | 201 | 400 | 401 | 404 | 500;
type Size = "sm" | "md" | "lg" | "xl";

function move(dir: Direction) { /* ... */ }
move("north");        // OK
move("up");           // Error: "up" ไม่อยู่ใน Direction — และ editor แนะนำตัวเลือกให้

ได้ทั้ง type safety, autocomplete, และ refactor — ดีกว่า string เปล่า ๆ มาก

widening — ทำไม let ไม่เก็บ literal

const a = "hello";    // a: "hello"    (literal — const แก้ไม่ได้)
let b = "hello";      // b: string     (widened — เพราะ let assign ค่าอื่นได้)

function greet(msg: "hi" | "hello") {}
greet(a);             // OK
greet(b);             // Error: string ไม่ assignable กับ "hi" | "hello"

let → widen เป็น type กว้าง (string, number, boolean) เพราะเปลี่ยนค่าได้

widening ใน object

const config = {
  method: "GET",       // property ของ object literal → widen เป็น string
};
// config: { method: string }

fetch("/api", config);  // ถ้า fetch รับ method: "GET" | "POST" → Error!

แก้ได้ 3 วิธี:

// 1. annotate
const config: { method: "GET" | "POST" } = { method: "GET" };

// 2. as const กับ property
const config = { method: "GET" as const };
// config: { method: "GET" }

// 3. as const กับทั้ง object
const config = { method: "GET" } as const;
// config: { readonly method: "GET" }

as const

as const บอก TS ว่า “อย่า widen — เก็บทุกอย่างเป็น literal และ readonly”:

const point = [10, 20] as const;
// readonly [10, 20]

const colors = ["red", "green", "blue"] as const;
// readonly ["red", "green", "blue"]

const settings = {
  theme: "dark",
  fontSize: 14,
  features: ["a", "b"],
} as const;
// { readonly theme: "dark"; readonly fontSize: 14; readonly features: readonly ["a", "b"] }

เทคนิค: union จาก array

const ROLES = ["admin", "editor", "viewer"] as const;
type Role = typeof ROLES[number];
// "admin" | "editor" | "viewer"

function setRole(role: Role) { /* ... */ }
setRole("admin");      // OK

// มีทั้ง runtime array (loop ได้) และ compile-time type — จาก source เดียว
for (const role of ROLES) { /* role: "admin" | "editor" | "viewer" */ }

literal type vs enum

TypeScript มี enum แต่มีข้อควรระวัง:

enum Direction {
  North,   // 0
  South,   // 1
  East,    // 2
  West,    // 3
}

enum Color {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE",
}

const d: Direction = Direction.North;

ปัญหาของ enum:

  • สร้าง runtime code — enum ไม่ถูกลบตอน compile (ต่างจาก type อื่น) เพิ่มขนาด bundle
  • numeric enum ไม่ปลอดภัย — Direction.North + 1 ได้ 1 (South), และรับค่านอก enum ได้บางกรณี
  • const enum แก้เรื่อง runtime แต่มีปัญหากับ bundler บางตัว

ทางเลือกที่ community นิยม — union ของ literal + object:

const Direction = {
  North: "north",
  South: "south",
  East: "east",
  West: "west",
} as const;

type Direction = typeof Direction[keyof typeof Direction];
// "north" | "south" | "east" | "west"

function move(dir: Direction) { /* ... */ }
move(Direction.North);   // OK
move("north");           // OK ด้วย — literal ตรง ๆ ก็ได้

ได้ทั้ง namespace (Direction.North), type safety, และ ไม่มี runtime overhead เกินจำเป็น

เมื่อไรใช้ enum ได้: มี string enum, ทีมคุ้นเคย, ไม่กังวล bundle size — ไม่ผิด แค่รู้ trade-off

literal type กับ template

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

type CssUnit = `${number}px` | `${number}em` | `${number}%`;

(บทที่ 37 ว่าด้วย template literal types)

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

  • let x = "GET" แล้วส่งเข้าฟังก์ชันที่รับ "GET" | "POST" — x widened เป็น string; ใช้ const หรือ as const
  • property ของ object literal widen — { method: "GET" } เป็น { method: string }; as const
  • ใช้ enum โดยไม่รู้ว่ามัน emit runtime code
  • numeric enum แล้วพึ่งค่าตัวเลข — เปราะ ใช้ string enum หรือ literal union
  • as const แล้วลืมว่ามันทำ readonly — เข้าถึงได้ แก้ไม่ได้; ถ้าจะแก้ต้อง clone
  • typeof arr[number] โดยไม่มี as const — ได้ string ไม่ใช่ union ของ literal

สรุป

  • literal type — ค่าเดียวเป๊ะ ("admin", 200); union ของ literal = enum-like ที่มี autocomplete + type safety
  • let widen literal เป็น type กว้าง; const เก็บ literal ไว้
  • as const — freeze เป็น literal + readonly (ทั้ง value และ nested)
  • const ROLES = [...] as const; type Role = typeof ROLES[number] — union จาก array (source เดียว, ทั้ง runtime + type)
  • enum สร้าง runtime code และ numeric enum ไม่ปลอดภัย — union ของ literal + as const object มักดีกว่า
  • template literal type: `${number}px`

บทถัดไปว่าด้วย type alias เทียบ interface — ความต่าง, declaration merging และเมื่อไรใช้อะไร