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