Start learning free

LESSON 645 OF 675 · OBJECT-ORIENTED PROGRAMMING

Interfaces in TypeScript

Lesson

TL ; DR:

An interface is a pure contract — a list of methods that a class promises to implement, with no shared data and no shared code. Unlike inheritance ("is a"), interfaces express "can do".


interface Speaker {
    speak(): void;
}
class Dog implements Speaker {
    speak(): void { console.log("Woof"); }
}


Full lesson:

An interface defines what a class can do, not how it does it or what it is. A Truck, a Robot, and a Drone aren't the same kind of thing — but they can all move(). You'd put move() in a Movable interface and have each one implement it.

Interface vs abstract class

Abstract classInterface
Has fieldsYesOnly declares them (no values)
Has method bodiesYes (some)No (signatures only)
Multiple "inheritance"NoYes — a class can implement many interfaces
Models"is a""can do"

A class inherits from at most one parent class but can implement many interfaces. That's why interfaces are the right tool for cross-cutting capabilities like Comparable, Serializable, Iterable, etc.

Interfaces in TypeScript:

TypeScript has a real interface keyword. An interface describes the shape an object or class must have — the methods and properties it must provide — and a class then implements it.

interface Speaker {
    speak(): void;
}

class Dog implements Speaker {
    speak(): void { console.log("Woof"); }
}

The implements keyword makes the compiler check that Dog really provides every member Speaker requires — which is exactly what you'll do in the task below. Interfaces exist only at compile time: they are erased from the compiled JavaScript.


Your task

The Speaker interface is already declared. Create a Dog class that implements it, with a speak() method that prints "Woof".

Expected output:

Woof
STEP 1 OF 2
    Ctrl + Enter to check