אובייקטים: type ו-interface
רוב הנתונים באפליקציה הם אובייקטים: משתמש, מוצר, הזמנה. בשיעור הזה נלמד לתאר את הצורה שלהם, ונפתור את השאלה הנצחית "type או interface".
תיאור אובייקט עם type
type Product = {
id: number;
name: string;
price: number;
description?: string; // אופציונלי
readonly sku: string; // אי אפשר לשנות אחרי יצירה
};
const pen: Product = { id: 1, name: 'עט', price: 5, sku: 'PEN-01' };
pen.sku = 'X';
// Cannot assign to 'sku' because it is a read-only property.
const broken: Product = { id: 2, name: 'מחק' };
// Property 'price' is missing in type ... but required in type 'Product'.
אותו דבר עם interface
interface Product {
id: number;
name: string;
price: number;
}
אז type או interface?
type | interface | |
|---|---|---|
| תיאור אובייקט | ✅ | ✅ |
| Union, Tuple, טיפוס פונקציה | ✅ | ❌ |
| הרחבה | & | extends |
| הרחבה של הגדרה קיימת (declaration merging) | ❌ | ✅ |
המלצה פשוטה: בחרו אחד ותהיו עקביים. הקורס משתמש ב-type, כי הוא עושה הכול. interface מצוין כשכותבים ספרייה שאחרים צריכים להרחיב.
הרחבה והרכבה
type Entity = {
id: number;
createdAt: Date;
};
// & מחבר שני טיפוסים: יש את כל השדות של שניהם
type User = Entity & {
name: string;
email: string;
};
// באותו רעיון עם interface
interface Admin extends User {
permissions: string[];
}
אובייקטים מקוננים ומערכים
type Order = {
id: number;
customer: {
name: string;
address: { city: string; street: string };
};
items: { productId: number; quantity: number }[];
};
function citiesOf(orders: Order[]): string[] {
return orders.map((order) => order.customer.address.city);
}
כשמבנה מקונן חוזר בכמה מקומות, מוציאים אותו לטיפוס משלו (type Address = ...).
מילון: מפתחות שלא ידועים מראש
// כל מפתח הוא string, כל ערך הוא number
type Stock = Record<string, number>;
const stock: Stock = { pen: 40, eraser: 12 };
stock.ruler = 7;
// מפתחות מקבוצה סגורה
type Role = 'admin' | 'editor';
const labels: Record<Role, string> = {
admin: 'מנהל',
editor: 'עורך',
}; // שכחתם תפקיד? שגיאה
"שדה מיותר" - בדיקה שמגינה מטעויות כתיב
const item: Product = { id: 3, name: 'סרגל', price: 8, sku: 'R-1', colour: 'blue' };
// Object literal may only specify known properties, and 'colour' does not exist in type 'Product'.
כשכותבים אובייקט ישירות, TypeScript מתריעה על שדה שלא בטיפוס. ככה נתפסות טעויות כתיב כמו colour במקום color.
בדקו את עצמכם
נסו לענות לבד לפני שאתם פותחים את התשובה.
-
מה עושה
readonlyעל שדה?הצגת התשובה
תשובה ג. ניסיון השמה ל-readonly מסומן כשגיאה.
-
מה ההמלצה לגבי type מול interface?
הצגת התשובה
תשובה ב. שניהם מתארים אובייקטים. ההבדלים קטנים בשימוש יומיומי.