TypeScript any, unknown, never และ type assertion



any — ปิด type check (เลี่ยง)

let x: any = 42;
x.foo.bar();          // OK ตอน compile — crash ตอน runtime
x();                  // OK
x + true;             // OK
const y: string = x;  // OK — any assign ให้อะไรก็ได้

function process(data: any) {
  return data.items.map((i: any) => i.value);   // ไม่มีการตรวจอะไรเลย
}

any แพร่กระจาย — ค่าที่ได้จาก any กลายเป็น any ต่อ:

const config: any = loadConfig();
const port = config.port;       // port: any
const url = `http://localhost:${port}`;   // ยังไม่มีการตรวจ

ตั้ง "noImplicitAny": true (มากับ strict) — implicit any (พารามิเตอร์ไม่มี type ฯลฯ) เป็น error ต้องเขียนชัด ๆ

เมื่อไรใช้ any ได้: migration จาก JS (ชั่วคราว), 3rd-party ที่ type พัง, prototype — แต่มาร์กไว้ (// TODO: type this)

unknown — any ที่ปลอดภัย

let x: unknown = getData();

x.foo;                // Error: 'x' is of type 'unknown'
x();                  // Error
const y: string = x;  // Error: unknown ไม่ assign ให้ string

// ต้อง narrow ก่อนใช้
if (typeof x === "string") {
  x.toUpperCase();    // OK
}

if (x instanceof Error) {
  console.log(x.message);
}

// หรือ type guard
if (isUser(x)) {
  x.name;
}

ใช้ unknown แทน any สำหรับ: JSON.parse result, catch (e), ข้อมูล API, function ที่รับ “อะไรก็ได้”

function safeParse(json: string): unknown {
  return JSON.parse(json);   // อย่าคืน any — คืน unknown บังคับ caller ให้ validate
}

const data = safeParse(input);
if (isValidResponse(data)) {   // narrow
  data.result;
}

never — ไม่มีค่าใดเป็นไปได้

// function ที่ไม่มีวัน return
function throwError(msg: string): never {
  throw new Error(msg);
}

function infiniteLoop(): never {
  while (true) {}
}

// type ที่เป็นไปไม่ได้
type Impossible = string & number;   // never

// exhaustiveness check (บทที่ 23)
function assertNever(x: never): never {
  throw new Error(`unexpected: ${x}`);
}

// filter type ใน conditional
type NonNullable<T> = T extends null | undefined ? never : T;

never เป็น subtype ของทุก type — assign never ให้อะไรก็ได้ (แต่ไม่มีค่า never ที่จะ assign จริง)

void — ไม่คืนค่า

function log(msg: string): void {
  console.log(msg);   // อาจมี return; เปล่า ๆ ได้ แต่ห้าม return value
}

// void ในตำแหน่ง callback — ผู้ implement คืนค่าอะไรก็ได้ (TS ละเลย)
[1, 2, 3].forEach((n) => n * 2);   // OK — callback คืน number แต่ signature เป็น void

void ≠ undefined — void = “ไม่สนค่าที่คืน”, undefined = “ค่าเป็น undefined เท่านั้น”

type assertion — as

value as Type = “TS เชื่อฉันว่ามันเป็น Type นี้” — ไม่มีการตรวจ runtime, ไม่มีการแปลง:

const input = document.getElementById("name") as HTMLInputElement;
input.value;   // OK — เพราะ assert ว่าเป็น input

const data = JSON.parse(json) as User;   // ⚠️ ไม่ได้ validate ว่าเป็น User จริง
data.name;   // อาจ undefined ตอน runtime

assertion ทำได้เฉพาะระหว่าง type ที่ “overlap” — บังคับด้วย double assertion (อันตราย):

const x = "hello" as unknown as number;   // TS ยอม (ผ่าน unknown) — เกือบทุกครั้งคือบั๊ก

as const — literal + readonly (ทบทวน)

const config = { host: "localhost", port: 8080 } as const;
// { readonly host: "localhost"; readonly port: 8080 }

satisfies — เช็คว่าตรง type แต่เก็บ type ที่แคบไว้ (TS 4.9+)

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

// ❌ as — สูญเสีย type ที่แคบ
const config1 = {
  host: "localhost",
  port: 8080,
} as Config;
config1.port.toFixed();   // Error: port เป็น string | number

// ✅ satisfies — เช็คว่าตรง Config แต่ port ยังเป็น number
const config2 = {
  host: "localhost",
  port: 8080,
} satisfies Config;
config2.port.toFixed();   // OK — port: number
config2.host.toUpperCase();  // OK — host: string

satisfies = “เช็คว่า expression นี้ assignable กับ type — แต่อย่า widen มันเป็น type นั้น”

ตัวอย่างที่ทรงพลัง:

const routes = {
  home: "/",
  about: "/about",
  user: (id: string) => `/users/${id}`,
} satisfies Record<string, string | ((...args: any[]) => string)>;

routes.home;            // "/" (literal)
routes.user("123");     // "/users/123" — TS รู้ว่าเป็น function

as vs satisfies vs annotation

const a: Config = { host: "x", port: 1 };        // annotation — เช็ค + widen เป็น Config
const b = { host: "x", port: 1 } as Config;       // assertion — เชื่อ + widen (ไม่เช็คเข้ม)
const c = { host: "x", port: 1 } satisfies Config; // เช็ค + เก็บ type แคบ (แนะนำ)

เลือก satisfies เมื่ออยากทั้ง (1) เช็คว่าตรง type (2) เก็บ inference ที่แคบ

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

  • any เพื่อ “ให้ผ่าน” — ปิด type check + แพร่กระจาย; ใช้ unknown + narrow
  • as แทน validation — JSON.parse(x) as User ไม่ตรวจ runtime; ใช้ zod/type guard (บทที่ 30)
  • as unknown as T (double assertion) — เกือบทุกครั้งคือบั๊ก; หา root cause
  • void return type แล้วคาดว่าค่าเป็น undefined — void = “ไม่สนค่าคืน”
  • never ใน union — string | never = string (never หายไป)
  • as Config แล้วสูญเสีย literal type — ใช้ satisfies Config
  • catch (e) แล้ว e.message — e เป็น unknown (TS 4.4+); narrow ด้วย e instanceof Error

สรุป

  • any — ปิด type check, แพร่กระจาย — เลี่ยง (noImplicitAny)
  • unknown — “ไม่รู้ ต้อง narrow ก่อนใช้” — ใช้แทน any สำหรับ JSON.parse, catch, API data
  • never — ไม่มีค่าเป็นไปได้ (function ที่ throw/loop, exhaustiveness check, filter ใน conditional type)
  • void — ไม่คืนค่า (≠ undefined); ใน callback = ละเลยค่าคืน
  • as Type — เชื่อโดยไม่ตรวจ runtime; as unknown as T = อันตราย
  • satisfies Type (4.9+) — เช็คว่าตรง type แต่เก็บ inference ที่แคบ — แนะนำ สำหรับ config object

บทถัดไปว่าด้วย async, Promise และ await — Promise<T>, return type ของ async function, Promise.all และ catch ที่เป็น unknown