अपने object types को मॉडल और compose करने के लिए सही construct चुनें, बिना code दोहराए।
इस पाठ को Kodokon में खोलेंआप पहले से ही object types घोषित करना जानते हैं। किसी project पर असली सवाल है type और interface के बीच चुनाव करना, और फिर मौजूदा types को compose करना बिना code दोहराए। सबसे आम परिदृश्य से शुरू करते हैं: ऐसी entities को मॉडल करना जो एक जैसी दिखती हैं।
interface User {
id: number;
name: string;
}
interface Admin extends User {
permissions: string[];
}
const admin: Admin = {
id: 1,
name: "Ada",
permissions: ["users:write"],
};extends एक स्पष्ट संबंध बनाता है: एक Admin वह User है जिसके पास अतिरिक्त शक्तियाँ हैं। एक type alias के साथ, आपको वही परिणाम intersection operator & के ज़रिए मिलता है, जो कई shapes को एक में मिला देता है। यह cross-cutting concerns के लिए एकदम सही उपकरण है, जैसे कि आपकी सभी entities पर मौजूद timestamps।
type Timestamps = {
createdAt: Date;
updatedAt: Date;
};
type Product = {
id: number;
label: string;
};
type StoredProduct = Product & Timestamps;तो आपको कौन-सा चुनना चाहिए? दो अंतर वाकई मायने रखते हैं। पहला, केवल type ही 'active' | 'archived' जैसे union को नाम दे सकता है। दूसरा, एक ही नाम साझा करने वाली दो interface घोषणाएँ अपने-आप merge हो जाती हैं: किसी library के types को augment करने के लिए सुविधाजनक, पर जब यह गलती से हो तो ख़तरनाक।
type Status = "active" | "archived";
interface Config {
locale: string;
}
interface Config {
debug: boolean;
}
const config: Config = { locale: "fr", debug: true };