Chapter 5TypeScript~1 min read
Interfaces आणि Type Aliases
Custom Types बनवा
Inline object types वारंवार लिहणे tedious आहे. Interface किंवा Type Alias वापरून custom types बनवता येतात आणि reuse करता येतात.
Interface
typescript
// Interface define करा
interface Student {
id: number;
name: string;
age: number;
email?: string; // optional
readonly rollNo: string; // read-only
}
// Use करा
const student: Student = {
id: 1,
name: "Avadhoot",
age: 22,
rollNo: "CS101",
};
student.rollNo = "CS102"; // ❌ ERROR: readonly
// Interface extend करा
interface GradStudent extends Student {
thesis: string;
supervisor: string;
}Type Alias
typescript
// Type alias
type Point = {
x: number;
y: number;
};
// Union type alias
type Status = "active" | "inactive" | "pending";
// Intersection type
type AdminUser = Student & {
adminLevel: number;
permissions: string[];
};
let userStatus: Status = "active";
userStatus = "deleted"; // ❌ ERROR — not in unionInterface vs Type — कधी काय?
- ▸Interface — objects describe करण्यासाठी, extend होतात
- ▸Type — unions, intersections, primitives साठी
- ▸Objects साठी Interface prefer केलं जातं
- ▸React props साठी दोन्ही चालतात — team convention follow करा
✅ Key Points — लक्षात ठेवा
- ▸Interface — reusable object shape
- ▸readonly — property immutable बनवतो
- ▸optional (?) — property required नाही
- ▸extends — interface inherit करा
- ▸Type union: "a" | "b" | "c"
0/9 chapters पूर्ण