intermediate#TypeScript#Interfaces#Objects
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.