TypeScript array method และ iteration ให้ type ถูก



map / filter — infer ได้ดี

const nums = [1, 2, 3, 4, 5];

const doubled = nums.map((n) => n * 2);           // number[]
const strings = nums.map((n) => `#${n}`);         // string[]
const objects = nums.map((n) => ({ id: n }));     // { id: number }[]

const evens = nums.filter((n) => n % 2 === 0);    // number[]

callback parameter n infer เป็น number จาก type ของ array (contextual typing)

filter + type guard — narrow

const mixed: (string | null)[] = ["a", null, "b", null];

const clean = mixed.filter((x) => x !== null);
// clean: (string | null)[]  ← type ไม่ narrow!

const clean2 = mixed.filter((x): x is string => x !== null);
// clean2: string[]

// helper
function isNotNull<T>(x: T | null): x is T {
  return x !== null;
}
const clean3 = mixed.filter(isNotNull);   // string[]

TS 5.5+ ปรับปรุง inference ให้ filter((x) => x !== null) narrow ได้ในบางกรณี — แต่ helper ยังชัวร์กว่า

reduce — มักต้องระบุ type

const nums = [1, 2, 3, 4];

// number accumulator — infer ได้จาก initial value
const sum = nums.reduce((acc, n) => acc + n, 0);   // number

// object accumulator — ต้องระบุ
const grouped = nums.reduce(
  (acc, n) => {
    const key = n % 2 === 0 ? "even" : "odd";
    (acc[key] ??= []).push(n);
    return acc;
  },
  {} as Record<"even" | "odd", number[]>,   // ระบุ type ของ acc
);

// หรือ generic parameter
const map = nums.reduce<Map<number, number>>(
  (acc, n) => acc.set(n, n * n),
  new Map(),
);

{} initial value infer เป็น {} (empty) — accumulator ที่ต้อง build ขึ้นต้อง as Type หรือ reduce<Type>(...)

flatMap

const sentences = ["hello world", "foo bar baz"];
const words = sentences.flatMap((s) => s.split(" "));   // string[]
// ["hello", "world", "foo", "bar", "baz"]

find / findIndex / some / every

const users = [{ id: 1, name: "อร" }, { id: 2, name: "บอย" }];

const user = users.find((u) => u.id === 1);       // { id: number; name: string } | undefined
const index = users.findIndex((u) => u.id === 3); // number (-1 ถ้าไม่เจอ)
const hasAdmin = users.some((u) => u.name === "admin");   // boolean
const allNamed = users.every((u) => u.name.length > 0);   // boolean

// find อาจ undefined — เช็คก่อนใช้
if (user) {
  user.name;
}

ReadonlyArray

function sum(nums: readonly number[]): number {
  // nums.push(1);   // Error — ป้องกันการแก้ array ของผู้เรียก
  return nums.reduce((a, b) => a + b, 0);
}

const data: ReadonlyArray<string> = ["a", "b"];
data[0] = "c";        // Error
data.sort();          // Error (sort แก้ในตัว)
[...data].sort();     // OK — spread เป็น array ใหม่

Object.keys / values / entries — typing ที่ต้องระวัง

const user = { id: 1, name: "อร", active: true };

Object.keys(user);      // string[]   ← ไม่ใช่ ("id" | "name" | "active")[]!
Object.values(user);    // (string | number | boolean)[]
Object.entries(user);   // [string, string | number | boolean][]

// วน entries
for (const [key, value] of Object.entries(user)) {
  // key: string, value: string | number | boolean
}

Object.keys คืน string[] เสมอ (design decision — object อาจมี key มากกว่าที่ type บอก จาก prototype) ถ้าต้องการ typed keys:

function typedKeys<T extends object>(obj: T): (keyof T)[] {
  return Object.keys(obj) as (keyof T)[];   // assertion — รับผิดชอบเอง
}

for (const key of typedKeys(user)) {
  user[key];   // key: "id" | "name" | "active"
}

for…of vs for…in vs forEach

const arr = [10, 20, 30];

// for...of — วน value (นิยม)
for (const value of arr) {
  value;   // number
}

// for...in — วน key (เป็น string!) — เลี่ยงกับ array
for (const index in arr) {
  index;   // string ("0", "1", "2") — ต้อง Number(index)
}

// entries() — ได้ทั้ง index และ value
for (const [i, value] of arr.entries()) {
  i;       // number
  value;   // number
}

// forEach — ไม่รองรับ break/continue, ไม่รอ async
arr.forEach((value, index) => { });

ใช้ for...of เป็นค่าเริ่มต้น; .entries() เมื่อต้อง index; หลีกเลี่ยง for...in กับ array

typing this ใน array method (rare)

// ถ้าใช้ function ปกติ (ไม่ใช่ arrow) เป็น callback + ต้อง this
[1, 2, 3].map(function (n) {
  return n * this.factor;   // this: any — ต้องส่ง thisArg
}, { factor: 2 });

ใช้ arrow function เลี่ยงปัญหานี้

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

  • filter((x) => x != null) แล้วคาดว่า narrow — ใช้ type guard (x): x is T หรือ helper (TS < 5.5)
  • reduce object accumulator ไม่ระบุ type — {} initial → acc เป็น {}; as Record<...> หรือ reduce<Type>
  • Object.keys(obj) คาดว่าได้ typed keys — ได้ string[]; ใช้ as (keyof T)[] helper
  • for...in กับ array — วน key เป็น string, รวม property จาก prototype; ใช้ for...of
  • find แล้วใช้ต่อไม่เช็ค — คืน T | undefined
  • แก้ array ที่รับเป็น parameter — ใช้ readonly T[]
  • forEach กับ async callback — ไม่รอ (บทที่ 26)

สรุป

  • map/filter/flatMap/find — TS infer callback param + return type จาก array
  • filter narrow ต้องใช้ type guard (x): x is T => ... (หรือ helper isNotNull)
  • reduce object/map accumulator — ระบุ type: reduce<T>(...) หรือ initial as T
  • readonly T[] / ReadonlyArray<T> — พารามิเตอร์ที่ไม่ควรแก้
  • Object.keys คืน string[] (ไม่ใช่ keyof T[]) — helper + assertion ถ้าต้องการ typed
  • for...of (value) เป็นค่าเริ่มต้น; .entries() (index+value); เลี่ยง for...in กับ array

บทถัดไปว่าด้วยการทำงานกับ DOM และ event (ฝั่งเบราว์เซอร์) — lib.dom, querySelector generics และ event types