The type annotation is long. What happens if we need to create more functions? We'll have to repeat our annotation. Additionally, what if we add more properties? That's even more maintenance.
Note: Behind the scenes, an interface works because TypeScript loops through the object's properties and methods and checks that it satisifes the interface's shape. (This includes non-primitive data types and functions too.)
Refactor: Sufficiency of Interfaces
Suppose that our printVehicle function only uses 1 property from the vehicle parameter.
Do we really need every other property/method in our Vehicle interface? No! We only care about the properties/methods that are sufficient for our use case.
Now we've created a more generic interface that can be reused in more places!
Code Reuse with Interfaces
We can now reuse Identifiable with other very different objects. As long as the object has the name property as a string, it is considered an Identifiable type.
Pro tip: Interfaces are the encouraged pattern to promote code reuse in your applications. As much as possible, use an interface to gatekeep your functions, and then create objects/classes that implement those interfaces to pass them into your functions.
// Note: we rename the interface b/c with so few properties,
// it's not really a vehicle anymore
interface Identifiable {
name: string;
}
const printVehicle = (vehicle: Identifiable): void => {
console.log(vehicle.name);
};
const drink = {
name: 'Pepsi',
color: 'brown',
carbonated: true,
sugar: 40,
};
// We rename the function to be more generic
const printName = (item: Identifiable): void => {
console.log(item.name);
j;
};