Understanding TypeScript Interfaces
This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.
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? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based TypeScript courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for TypeScript books — check the publication year so the examples match current versions.
Search Amazon →