intermediate#TypeScript#interfaces#object-oriented
Understanding TypeScript Interfaces
Learn how to use interfaces in TypeScript to define the shape of objects and improve code maintainability.
Introduction to Interfaces
In TypeScript, an interface is used to define the shape of an object. It specifies the properties, methods, and their types that an object must have.
Defining an Interface
Here's an example of how to define an interface:
interface Person {
name: string;
age: number;
}
Using an Interface
Once you've defined an interface, you can use it to type-check objects:
const person: Person = {
name: 'John Doe',
age: 30
};
Extending an Interface
You can extend an interface using the extends keyword:
interface Employee extends Person {
department: string;
}
Implementing an Interface
You can implement an interface using the implements keyword:
class PersonImpl implements Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}