

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Classes
incomplete
2: Private Class Members
incomplete
3: TypeScript Public and Private
incomplete
4: Protected Data Members
incomplete
5: Abstract Classes and Methods
incomplete
6: Classes Implement Interfaces
incomplete
7: Classes vs. Interfaces and Types
incomplete
8: The 'this' Type
incomplete
9: Parameter Properties
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Classes can implement interfaces using the implements clause. This enforces that the class adheres to the structure defined by the interface. Say we have two interfaces:
interface Vehicle {
make: string;
model: string;
}
interface Drivable {
drive(distance: number): void;
}
And we have a class that we want to implement (have the properties and methods of) both interfaces:
class ElectricCar {
make: string;
model: string;
}
We can add a clause to the class definition to implement both interfaces. However, because at the moment, the class doesn't have a drive method, TypeScript will throw an error:
// Error: Class 'ElectricCar' incorrectly implements interface 'Drivable'.
class ElectricCar implements Vehicle, Drivable {
make: string;
model: string;
}
So, now we're reminded to add the drive method, and we do so:
class ElectricCar implements Vehicle, Drivable {
make: string;
model: string;
// not required by the interfaces, but it's
// okay to add extra properties
private isRunning: boolean = false;
constructor(make: string, model: string) {
this.make = make;
this.model = model;
this.isRunning = false;
}
drive(distance: number): void {
this.isRunning = true;
console.log(`Driving ${distance} miles`);
}
}
We can now use an instance of ElectricCar as a Vehicle or Drivable:
const myCar = new ElectricCar("Tesla", "Model S");
function testDrive(vehicle: Vehicle) {
console.log(`Testing ${vehicle.make} ${vehicle.model}`);
}
testDrive(myCar); // "Testing Tesla Model S"
function takeForARide(drivable: Drivable) {
drivable.drive(10);
}
takeForARide(myCar); // "Driving 10 miles"
Let's refactor the code to use interfaces.