Understanding TypeScript Interfaces
Learn about TypeScript interfaces and how to use them to define contracts for your objects.
Introduction to Interfaces
In TypeScript, an interface is a way to define a contract that an object must adhere to. It specifies a set of properties, methods, and their types that an object must have.
Step 1: Define an Interface
Create a new file called person.ts and add the following code:
interface Person {
name: string;
age: number;
}
This code defines an interface called Person with two properties: name and age.
Step 2: Implement the Interface
Add the following code to the person.ts file:
class Employee implements Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
This code defines a class called Employee that implements the Person interface.
Step 3: Use the Interface
Create a new file called main.ts and add the following code:
const employee: Person = new Employee('John Doe', 30);
console.log(employee.name);
console.log(employee.age);
This code creates a new Employee object and assigns it to a variable of type Person. It then logs the name and age properties of the object to the console.
Ready for more? These paid resources pick up where this lesson leaves off.
Project-based TypeScript video courses — the perfect paid next step after these free lessons.
Browse on Udemy →Hand-picked TypeScript books to master the fundamentals offline.
See on Amazon →Some links on this page are affiliate links: we may earn a commission at no extra cost to you. We only recommend tools we believe are genuinely useful.