ทั้งสองอธิบายรูปร่างของข้อมูล และมักจะใช้แทนกันได้ แต่มีความสามารถที่แตกต่างกัน
ts
interface User { name: string; age: number; }
type User2 = { name: string; age: number; };
ทั้งสองอธิบายรูปร่างของข้อมูล และมักจะใช้แทนกันได้ แต่มีความสามารถที่แตกต่างกัน
interface User { name: string; age: number; }
type User2 = { name: string; age: number; };
typeinterfacetype ID = string | number; // unions
type Pair = [number, number]; // tuples
type Name = User["name"]; // indexed/mapped/conditional types
type Nullable<T> = T | null; // wrap any type
type คือ alias ทั่วไปสำหรับประเภทใดๆ — primitives, unions, tuples, mapped types interface อธิบายเพียงรูปร่าง object/function เท่านั้น
interface ทำได้แต่ type ไม่ได้interface Box { width: number; }
interface Box { height: number; } // declaration merging — both merge into one
// Box now has width AND height
Interfaces รองรับ declaration merging (การรวมหลายการประกาศ) และเป็นวิธี idiomatic ในการขยาย/เพิ่มเติม รวมถึงการเพิ่มเติมประเภทไลบรารีของบุคคลที่สาม
interface Admin extends User { role: string; } // interface
type Admin2 = User & { role: string }; // type uses intersection
อนุสัญญาทั่วไป: ใช้ interface สำหรับรูปร่าง object และ public API (ข้อความข้อผิดพลาดที่ดีกว่า ขยายได้ รวมได้) และ type เมื่อต้องการ unions, tuples หรือการทำงานประเภทอื่นๆ เลือกหนึ่งเป็นค่าเริ่มต้นเพื่อความสอดคล้อง — ทีมจำนวนมากใช้ interface เป็นค่าเริ่มต้นสำหรับ objects และใช้ type เฉพาะเมื่อต้องการกำลังเพิ่มเติมของมัน