Interfaces in TypeScript play a crucial role in defining the structure of objects and classes, ensuring that they adhere to specific contracts and facilitating code reuse. This article will explore various aspects of interfaces, including their methods, parameters, reopening, extension, and multiple interface implementations.
Introduction to Interfaces
Interfaces serve a purpose similar to type aliases but with a distinct syntax. They enable the creation of reusable types that describe the shape of objects.
interface Human {
name: string;
}
Interface Methods
Interface methods in TypeScript are used to define the structure of an object or class that must implement specific methods. They provide a way to establish contracts, ensuring adherence to a predefined structure.
interface Communication {
greetings(): string;
}
In the above example, the Communication interface declares a single method, greetings, which accepts zero arguments and returns a string. An alternative syntax using arrow functions is also valid:
interface Communication {
greetings:() => string;
}
Interface Method parameters:
Interfaces can accept parameters in method declarations, offering flexibility in defining the required structure:
Example:
interface Product {
name: string;
price: number;
applyDiscount(amount: number): void;
}
const shoes: Product = {
name: "Maggi",
price: 50,
applyDiscount(amount: number) {
const newPrice = this.price * ( 1 - amount);
this.price = newPrice;
return this.price
}
};
Reopening Interfaces
Reopening interfaces involves adding more properties to an interface after its initial declaration:
Interface Dog{
name: string,
age: number,
}
interface Dog{
breed:string,
bark():string,
}
const police:Dog = {
name:"Police",
age: 0.5,
breed: "Shepherd",
bark() {
return "WOOF!"
}
}
Extending Interface
To avoid repetition and declare an interface with the exact properties of a previous one, the extends keyword can be used:
Interface Dog{
name: string,
age: number,
}
interface Dog{
breed:string,
bark():string,
}
interface ServiceDog extends Dog{
job: "drug sniffer" | "bomb" | "guide"
}
const chewy: ServiceDog = {
name: "Chewy",
age: 2.5,
breed: "Lab",
bark() {
return "Woof!"
},
job: "bomb"
Multiple Interfaces
Interfaces can extend multiple interfaces, enabling the combination of their properties:
Example:
interface Person{
name: string
}
interface Employee {
readonly Id : number,
email : string
}
interface Engineer extends Person, Employee{
level: string,
languages: string[]
}
const chinwe:Engineer = {
name: "Chinwe",
Id: 123897,
email:"clarefausty@gmail.com",
level: "senior",
languages: ["JS", "TypeScript"]
}
In summary, TypeScript interfaces provide a powerful mechanism for defining and structuring code, promoting maintainability and code reuse through contracts and well-defined structures.
Top comments (0)