Loading...
Loading...
In TypeScript, the implements keyword is used to force a class to conform to an interface.
This means the class must implement all properties and methods described in the interface. Otherwise TypeScript will throw a compilation error.
interface IAnimal {
name: string;
makeSound(): void;
}
class Dog implements IAnimal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound() {
console.log("Woof!");
}
}
What happens?
Dog must implement all properties and methods of interface IAnimal.interface Person {
name: string;
age: number;
}
class User implements Person {
name: string;
// Error: Property 'age' is missing
}
Can implement multiple interfaces separated by commas:
interface A {
a(): void;
}
interface B {
b(): void;
}
class C implements A, B {
a() {
console.log("A");
}
b() {
console.log("B");
}
}
Important:
implements works only at type level. In compiled JavaScript there are no interfaces.