An Interest In:
Web News this Week
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
Interface Segregation Principle in TypeScript
Clients shouldnt be forced to depend on methods they do not use.
The idea behind this principle is that it is better to have smaller and more specific interfaces rather than a big interface.
If we had just one interface that covered a lot of features, clients of that interface would have to implement behavior that they didn't need. Instead, if we have smaller interfaces, clients can implement just the needed behavior.
Another advantage is that when we update an interface, the changes will affect less clients, so there is less risk of breaking the code.
Remember that a class can implement multiple interfaces, so there is no need to include everything in just one interface.
In the following bad example we have an interface for animals with 2 methods: walk and fly.
As you can see, the Dog
class has to implement the method fly even though that class does not need it.
interface Animal { walk(): void; fly(): void;}class Dog implements Animal { walk() { console.log("Walking"); } fly() { throw new Error("Dogs cannot fly"); }}class Duck implements Animal { walk() { console.log("Walking"); } fly() { console.log("Flying"); }}
Following this principle we can split the Animal
interface into multiple ones. This way, the Dog
class will only have to implement the methods that it needs.
interface AnimalCanWalk { walk(): void;}interface AnimalCanFly { fly(): void;}class Dog implements AnimalCanWalk { walk() { console.log("Walking"); }}class Duck implements AnimalCanWalk, AnimalCanFly { walk() { console.log("Walking"); } fly() { console.log("Flying"); }}
Original Link: https://dev.to/jmalvarez/interface-segregation-principle-in-typescript-4dgb
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To