TypeScriptBeginner
Interface (ইন্টারফেস)
Interface কী, optional/readonly property, function interface, extends, declaration merging এবং type alias-এর পার্থক্য।
21টি অংশবাংলা ভাষায়
Interface হলো object-এর গঠন বর্ণনা করার আরেকটি শক্তিশালী উপায়। বিশেষত object-এর আকৃতি (shape) ধরতে interface খুবই জনপ্রিয় — বিশেষ করে বড় লাইব্রেরি ও framework-এ।
Interface কী?
interface এক ধরনের contract — একটি object-এ কোন কোন প্রপার্টি থাকবে, সেটি ঘোষণা করে। annotation কিংবা implements — দুই ভাবেই কাজে লাগে।
Basic Interface
interface User {
name: string;
age: number;
}
function greet(user: User): string {
return "হ্যালো, " + user.name;
}
const u: User = { name: "রহিম", age: 28 };
console.log(greet(u));Optional ও readonly
interface Profile {
name: string;
email?: string; // optional
readonly joinedAt: Date; // readonly
}
const p: Profile = {
name: "রহিম",
joinedAt: new Date(),
};
// p.joinedAt = new Date(); // ❌ readonlyFunction Interface
interface Comparator {
(a: number, b: number): number;
}
const sortBy: Comparator = (a, b) => a - b;
console.log(sortBy(3, 9)); // -6Nested Interface
interface Address {
city: string;
zip: string;
}
interface Customer {
name: string;
address: Address; // nested
}
const c: Customer = {
name: "করিম",
address: { city: "ঢাকা", zip: "1207" },
};Interface Extension (extends)
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
const myDog: Dog = {
name: "টমি",
breed: "স্প্যানিয়েল",
};Multiple Interface Extension
interface Printable {
print(): void;
}
interface Serializable {
toJSON(): string;
}
interface Report extends Printable, Serializable {
build(): string;
}
// Report-এ তিনটির সব দাবি একসাথে থাকেDeclaration Merging
একই নামের interface একাধিকবার ঘোষণা করা যায় — TypeScript মিশিয়ে (merge) একটি বড় interface বানিয়ে নেয়। type-এ এই সুবিধা নেই।
interface Window {
version: number;
}
interface Window {
appName: string;
}
// দুই ঘোষণা মিশে যায় → { version: number; appName: string }Interface vs Type Alias
| বিষয় | Interface | Type Alias |
|---|---|---|
| object টাইপের জন্য | সেরা পছন্দ | দারুণ |
| union / tuple | পারে না | পারে |
| extends | পারে | intersection (&) দিয়ে |
| declaration merging | পারে | পারে না |
| primitive alias | পারে না | পারে |
মুখস্থ নিয়ম
object-এর জন্য interface ডিফল্ট (সবচেয়ে বেশি সুবিধা), আর union/tuple/conditional টাইপের জন্য type। অনেক কোডবেসে দুইটিই মিশে ব্যবহৃত হয়।
শেষ প্যারায় নিজে practice করুন — কোড কপি করে নিজের এডিটরে চালিয়ে দেখুন।