An interface in TypeScript is used to define the structure or blueprint of an object or a class.
It only defines what properties and methods should exist, but not how they work.
Think of it as a rule book β if a class agrees to follow it, it must define everything that the interface declares.
interface Animal {
name: string;
makeSound(): void;
}
class Dog implements Animal {
name = "Tommy";
makeSound() {
console.log("Woof! πΆ");
}
}
const dog = new Dog();
dog.makeSound(); // Woof! πΆ
π Explanation:
Animal interface just says that any class implementing it must have a name property and a makeSound() method.Dog class follows that rule and provides its own implementation.So basically,
π Interface = "Yeh sab cheeze honi chahiye",
but "kaise hongi" β thatβs up to the class.
An abstract class is like a half-built blueprint β it can have some real methods (with code) and some abstract methods (without code).
You canβt directly create an object from an abstract class.
You must create a subclass that extends it and implements the abstract methods.
abstract class Animal {
constructor(public name: string) {}
// Abstract method β no body, must be defined by subclass
abstract makeSound(): void;
// Concrete method β real logic
move() {
****console.log(`${this.name} is moving...`);
}
}
class Dog extends Animal {
makeSound() {
console.log("Woof! πΆ");
}
}
const dog = new Dog("Buddy");
dog.move(); // Buddy is moving...
dog.makeSound(); // Woof! πΆ