Understanding TypeScript Interfaces
Learn about TypeScript interfaces and how to use them to define contracts.
Introduction to Interfaces
In TypeScript, an interface is a way to define a contract that must be implemented by a class.
Step 1: Define an Interface
Create a new file called person.ts and add the following code:
interface Person {
name: string;
age: number;
}
This interface defines a Person contract with name and age properties.
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 class 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 uses it as a Person.
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.