Interface बनाम Type Alias - कब उपयोग करें
In this page:
interface InterfaceName {
property: type;
}
type AliasName = TypeA | TypeB; // unions and intersections need type
Object Contracts के लिए Interfaces
Interfaces एक object की shape या एक class के public API describe करने के लिए natural choice हैं, क्योंकि वे declaration merging support करते हैं और एक contract की तरह clearly पढ़ते हैं जिसे दूसरा code implement करता है।
उदाहरण: Interfaces for Object Contracts
interface User {
name: string;
age: number;
}
const u: User = { name: "Ravi", age: 25 };
console.log(u);
Unions के लिए Type Aliases
Type aliases एक बार आपको एक union या intersection नाम देना हो तो बेहतर fit हैं, क्योंकि interfaces सिर्फ एक single object shape describe कर सकते हैं और "इनमें से एक" express नहीं कर सकते।
उदाहरण: Type Aliases for Unions
type Status = "pending" | "done" | "failed";
const s: Status = "pending";
console.log(s);
Types Extend और Compose करना
Interfaces और type aliases दोनों दूसरी shapes extend करना support करते हैं, लेकिन interfaces extends उपयोग करते हैं और एक ही नाम की कई declarations merge कर सकते हैं, जबकि type aliases इसके बजाय & intersection operator से shapes combine करते हैं।
उदाहरण: Extending and Composing Types
interface Base { id: number; }
interface User extends Base { name: string; }
type Tagged = Base & { tag: string };
const u: User = { id: 1, name: "Ravi" };
console.log(u);
Tuples और Function Types
Type aliases एक tuple की fixed-length, fixed-position shape या एक function की call signature सीधे नाम दे सकते हैं, जो इनमें से किसी को एक interface में wrap करने से ज़्यादा naturally पढ़ता है।
उदाहरण: Tuples and Function Types
type Point = [number, number];
type Callback = (value: number) => void;
const p: Point = [1, 2];
const log: Callback = (v) => console.log(v);
log(p[0]);
Practical Selection Rules
एक rule of thumb के रूप में: एक interface की ओर पहुंचें जब एक object या class shape model कर रहे हों जो बाद में extend हो सकती है, और unions, tuples, primitives, या किसी ऐसी चीज़ के लिए type alias की ओर पहुंचें जो plain object contract नहीं है।
उदाहरण: Practical Selection Rules
interface User { name: string; } // object contract -> interface
type Id = string | number; // union -> type alias
const u: User = { name: "Ravi" };
const id: Id = 42;
console.log(u, id);
- एक interface से union लिखने की कोशिश करना, जैसे
interface Status = "a" | "b", जो एक syntax error है, क्योंकि unions कोtypeचाहिए। - एक ही नाम से दो type aliases declare करना और उम्मीद करना कि वे interfaces की तरह merge हो जाएंगे।
- एक project के across similar objects के लिए बिना consistent rule के
interfaceऔरtypemix करना।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: