Defining and Using Interfaces in TypeScript
Interfaces in TypeScript are a powerful way to define contracts within your code. They describe the shape of objects, specifying the types of properties and methods that an object can have. This guide covers the basics of defining and using interfaces in TypeScript with practical examples.
Defining Interfaces
An interface in TypeScript is defined using the interface
keyword followed by the name of the interface. You can then specify the properties and methods that the interface should have:
interface Person {
name: string;
age: number;
greet(): void;
}
Implementing Interfaces
To use an interface, a class can implement it using the implements
keyword. The class must then define all the properties and methods specified by the interface:
class Employee implements Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): void {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const employee = new Employee("Alice", 30);
employee.greet(); // Output: Hello, my name is Alice and I am 30 years old.
Optional Properties
Interfaces can define optional properties using the ?
symbol. This indicates that the property is not required when implementing the interface:
interface Person {
name: string;
age?: number; // Optional property
}
const person: Person = { name: "Bob" };
console.log(person); // Output: { name: 'Bob' }
Readonly Properties
Properties can be marked as readonly
to prevent them from being modified after they are initialized:
interface Person {
readonly name: string;
age: number;
}
const person: Person = { name: "Charlie", age: 25 };
// person.name = "Dave"; // Error: Cannot assign to 'name' because it is a read-only property.
console.log(person); // Output: { name: 'Charlie', age: 25 }
Extending Interfaces
Interfaces can extend other interfaces, allowing you to build on existing contracts. This is useful for creating more complex types:
interface Person {
name: string;
age: number;
}
interface Employee extends Person {
jobTitle: string;
}
const employee: Employee = { name: "Eve", age: 28, jobTitle: "Developer" };
console.log(employee); // Output: { name: 'Eve', age: 28, jobTitle: 'Developer' }
Function Types
Interfaces can also be used to define function types. This is useful when you want to describe the signature of a function:
interface GreetFunction {
(name: string): string;
}
const greet: GreetFunction = (name: string): string => {
return `Hello, ${name}!`;
}
console.log(greet("Frank")); // Output: Hello, Frank!
Conclusion
Interfaces in TypeScript are a versatile tool for defining contracts and ensuring type safety in your code. By using interfaces, you can create clear and maintainable code structures, promote reusability, and improve collaboration within your development team.
Comments
Post a Comment