TypeScript object type และ interface
object type แบบ inline
function greet(user: { name: string; age: number }): string {
return `${user.name} อายุ ${user.age}`;
}
let point: { x: number; y: number } = { x: 10, y: 20 };คั่น property ด้วย ; (หรือ ,) ใน type
interface — ตั้งชื่อ object type
interface User {
name: string;
age: number;
email: string;
}
function greet(user: User): string {
return `สวัสดี ${user.name}`;
}
const alice: User = {
name: "อลิซ",
age: 25,
email: "alice@example.com",
};interface reuse ได้ทั่วโปรเจกต์ — เป็นสัญญาว่า object หน้าตาแบบนี้
optional property — ?
interface Config {
host: string;
port: number;
timeout?: number; // optional — มีหรือไม่มีก็ได้
retries?: number;
}
const c1: Config = { host: "localhost", port: 8080 }; // OK — ไม่ใส่ optional
const c2: Config = { host: "localhost", port: 8080, timeout: 30 };
function connect(config: Config) {
const timeout = config.timeout ?? 5000; // config.timeout เป็น number | undefined
}timeout?: number = timeout?: number | undefined — เข้าถึงแล้วอาจได้ undefined
readonly property
interface Point {
readonly x: number;
readonly y: number;
}
const p: Point = { x: 10, y: 20 };
p.x = 30; // Error: Cannot assign to 'x' because it is a read-only propertyreadonly บังคับตอน compile เท่านั้น (runtime แก้ได้) — บอกเจตนาว่า field นี้ไม่ควรเปลี่ยนหลังสร้าง
nested object
interface Company {
name: string;
address: {
city: string;
country: string;
};
employees: User[];
}
// หรือแยก interface
interface Address {
city: string;
country: string;
}
interface Company {
name: string;
address: Address;
employees: User[];
}method ใน interface
interface Calculator {
add(a: number, b: number): number;
subtract: (a: number, b: number) => number; // เขียนแบบ property ก็ได้
history: number[];
}index signature — key แบบไดนามิก
เมื่อไม่รู้ชื่อ key ล่วงหน้า:
interface StringMap {
[key: string]: string;
}
const translations: StringMap = {
hello: "สวัสดี",
bye: "ลาก่อน",
};
translations.goodmorning = "อรุณสวัสดิ์"; // OK — key อะไรก็ได้ที่เป็น string
translations.count = 5; // Error: number ไม่ใช่ string
// ผสม known key กับ index signature
interface Response {
status: number;
[header: string]: string | number; // known key ต้อง assignable กับ index type
}เข้าถึง key ที่ไม่มี → ได้ type ที่ประกาศ แต่ค่าจริงอาจ undefined:
const value = translations["nonexistent"]; // type: string, ค่าจริง: undefinedตั้ง "noUncheckedIndexedAccess": true ให้ TS เพิ่ม | undefined อัตโนมัติ (ปลอดภัยขึ้น)
Record<K, V> เป็นวิธีเขียนที่กระชับกว่า:
const translations: Record<string, string> = { hello: "สวัสดี" };
const permissions: Record<"read" | "write", boolean> = { read: true, write: false };excess property check
interface User {
name: string;
age: number;
}
const u: User = {
name: "อร",
age: 25,
role: "admin", // Error: Object literal may only specify known properties
};TS เตือนเมื่อ object literal มี property เกินจาก type — จับ typo (nmae แทน name)
แต่ผ่านตัวแปรกลาง จะไม่เตือน (structural typing):
const data = { name: "อร", age: 25, role: "admin" };
const u: User = data; // OK — data มี name, age ครบ (role ส่วนเกินไม่ถูก check)interface extends
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
const d: Dog = { name: "โฮ่ง", breed: "โกลเด้น" }; // ต้องมีทั้ง name และ breed
// extends หลายตัว
interface Pet extends Animal, HasOwner {
// ...
}type alias ก็ทำ object type ได้
type User = {
name: string;
age: number;
};type vs interface สำหรับ object แทบไม่ต่าง — บทที่ 9 ว่าด้วยความต่างและว่าเมื่อไรใช้อะไร
เรื่องที่คนมักพลาด
- เข้าถึง optional property โดยไม่เช็ค —
config.timeoutเป็นnumber | undefined; ใช้?? defaultหรือเช็ค - คิดว่า excess property check จับได้ทุกกรณี — ผ่านตัวแปรกลางจะไม่จับ (structural typing)
- index signature
[key: string]แล้วเข้าถึง key ที่ไม่มีแล้วคาดว่ามีค่า — เปิดnoUncheckedIndexedAccess readonlyแล้วคิดว่า runtime แก้ไม่ได้ — เป็น compile-time เท่านั้น (Object.freezeสำหรับ runtime)- ใช้
;ผิดกับ,ใน interface — ใช้ได้ทั้งคู่ แต่ทีมมัก;(gofmt-style) interface User {}(ว่าง) — รับ object อะไรก็ได้ (ยกเว้น null/undefined) — มักไม่ใช่ที่ต้องการ
สรุป
- object type:
{ name: string; age: number }— inline หรือตั้งชื่อด้วยinterface property?: T— optional (type เป็นT | undefined);readonly property— แก้ไม่ได้ (compile-time)- index signature
[key: string]: T— key แบบไดนามิก;Record<K, V>เขียนกระชับกว่า - excess property check — จับ property เกินใน object literal (แต่ไม่จับผ่านตัวแปรกลาง)
interface B extends A— สืบทอด propertynoUncheckedIndexedAccess— ทำให้obj[key]/arr[i]เป็นT | undefined(ปลอดภัยขึ้น)
บทถัดไปว่าด้วยฟังก์ชัน — type ของพารามิเตอร์และ return, optional/default/rest, function type และ overloads