TypeScript ชนิดข้อมูลพื้นฐานและ type inference



type annotation

เขียน : Type หลังชื่อตัวแปร/พารามิเตอร์:

let name: string = "สมชาย";
let age: number = 30;
let isActive: boolean = true;
let nothing: null = null;
let notDefined: undefined = undefined;

number ครอบทั้ง int และ float (JS ไม่มีแยก):

let count: number = 42;
let price: number = 19.99;
let hex: number = 0xff;
let big: bigint = 100n;   // bigint แยกต่างหาก

type inference — TypeScript เดาให้

ส่วนใหญ่ไม่ต้องเขียน annotation — TS infer จากค่า:

let name = "สมชาย";       // TS รู้ว่า name: string
let age = 30;             // age: number
let isActive = true;      // isActive: boolean

name = 42;                // Error: Type 'number' is not assignable to type 'string'

เขียน annotation เมื่อ:

  • พารามิเตอร์ฟังก์ชัน (TS infer ไม่ได้)
  • ตัวแปรที่ประกาศแยกจากการ assign
  • อยากบังคับ type ให้กว้าง/แคบกว่าที่ infer
// ✅ ปล่อยให้ infer
const count = 10;

// ✅ annotate พารามิเตอร์
function double(n: number) {
  return n * 2;             // return type infer เป็น number
}

// ✅ annotate เมื่อ assign ทีหลัง
let result: string;
if (condition) {
  result = "yes";
} else {
  result = "no";
}

const vs let — literal type

let x = "hello";           // x: string  (widened)
const y = "hello";         // y: "hello"  (literal type — เพราะ const แก้ไม่ได้)

const ให้ literal type — สำคัญมากกับ union (บทที่ 8)

any — ปิดการตรวจ type

let value: any = 42;
value = "now a string";    // OK
value = { anything: true }; // OK
value.foo.bar.baz;          // OK ตอน compile — พังตอน runtime
value();                    // OK ตอน compile — TypeError ตอน runtime

any = “อย่าตรวจอะไรเลย” — หลีกเลี่ยง มันแพร่กระจาย (ค่าที่มาจาก any กลายเป็น any หมด) และทำลายประโยชน์ของ TS

ตั้ง "noImplicitAny": true (มากับ strict) — บังคับให้ any ที่โผล่มาต้องเขียนชัด ๆ (จะได้เห็น)

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

let value: unknown = getData();

value.foo;                 // Error: 'value' is of type 'unknown'
value();                   // Error

// ต้อง narrow ก่อนใช้
if (typeof value === "string") {
  value.toUpperCase();     // OK — ตอนนี้ TS รู้ว่าเป็น string
}

if (typeof value === "object" && value !== null && "foo" in value) {
  // ...
}

unknown = “ไม่รู้ว่าเป็นอะไร ต้องเช็คก่อนใช้” — ใช้กับ JSON.parse, catch (e), ข้อมูลจาก API (บทที่ 25, 30)

void และ never (เกริ่น)

function log(msg: string): void {
  console.log(msg);        // ไม่ return ค่า
}

function fail(msg: string): never {
  throw new Error(msg);    // ไม่มีวัน return (throw เสมอ)
}

(บทที่ 25 ลงลึก)

Object, object, {}

let a: object = { x: 1 };      // ค่าที่ไม่ใช่ primitive (แทบไม่ใช้)
let b: {};                      // อะไรก็ได้ที่ไม่ใช่ null/undefined (สับสน — เลี่ยง)
let c: Record<string, unknown>; // "object ที่มี key เป็น string" — ชัดกว่า

ปกติเราเขียน object type แบบเจาะจง (บทที่ 5) ไม่ใช้ object เปล่า ๆ

strictNullChecks

ด้วย strict เปิด — null และ undefined ไม่ใช่ สมาชิกของทุก type:

let name: string = null;   // Error: Type 'null' is not assignable to type 'string'

let maybe: string | null = null;   // ต้องประกาศชัดว่ารับ null ได้

function len(s: string | null): number {
  return s.length;         // Error: 's' is possibly 'null'
  // ต้องเช็คก่อน:
  // if (s === null) return 0;
  // return s.length;
}

นี่คือ feature ที่มีค่าที่สุดของ TS — จับ “Cannot read property of undefined” ได้ก่อน runtime (บทที่ 24)

type ของ array และอื่น ๆ (เกริ่น)

let nums: number[] = [1, 2, 3];
let names: string[] = ["a", "b"];
let pair: [string, number] = ["age", 25];   // tuple

(บทที่ 4)

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

  • เขียน annotation ทุกที่ — const x: number = 5 ซ้ำซ้อน; ปล่อยให้ infer
  • ใช้ any เพื่อให้ error หาย — ปิด type check; ใช้ unknown + narrow
  • ลืมว่า let x = "a" ให้ string ไม่ใช่ "a" — ใช้ const หรือ as const ถ้าต้องการ literal
  • : null เป็น type ของตัวแปรที่จะ assign ค่าอื่นทีหลัง — ใช้ string | null
  • ไม่เปิด strictNullChecks — พลาดการจับ null/undefined bug (มากับ strict)
  • Number, String, Boolean (ตัวใหญ่) เป็น type — ผิด! ใช้ number, string, boolean (ตัวเล็ก)
  • typeof x === "object" แล้วคิดว่าไม่ null — typeof null === "object" ต้องเช็ค x !== null ด้วย

สรุป

  • ชนิดพื้นฐาน (ตัวเล็ก): string, number (ครอบ int+float), boolean, bigint, null, undefined
  • type inference — TS เดาให้จากค่า; เขียน annotation เฉพาะพารามิเตอร์ฟังก์ชัน / assign ทีหลัง / บังคับ type
  • const → literal type ("hello"), let → widened (string)
  • any = ปิด type check (เลี่ยง), unknown = ต้อง narrow ก่อนใช้ (ปลอดภัย)
  • strictNullChecks — null/undefined ต้องประกาศชัด (string | null) และเช็คก่อนใช้

บทถัดไปว่าด้วย array และ tuple — T[], readonly, และ tuple type