implements
| Interfaces as contracts | |
| Many interfaces | |
| TS checks statically | |
| Refactor safely |
Interfaces as contracts
An interface lists the members a value must have. A class with implements promises to provide every member of that interface.
interface Named {
name: string;
}
class User implements Named {
name: string = "Ada";
}
Many interfaces
One class can implement several interfaces at once. List them after implements and provide members for each of them.
interface Printable {
print(): string;
}
interface Savable {
save(): void;
}
class Doc implements Printable, Savable {
print(): string {
return "doc";
}
save(): void {
console.log("saved");
}
}
TS checks statically
The compiler checks implements without running the code. A missing member is a build error, so broken classes never reach users.
Removing the name field below would fail the build with a clear message about the missing member.
interface Named {
name: string;
}
class Guest implements Named {
name: string = "Guest";
}
Refactor safely
Interfaces make large changes safe. Add a member to the interface and the compiler points to every class that needs an update.
interface Named {
name: string;
greet(): string;
}
class User implements Named {
name: string = "Ada";
greet(): string {
return "Hello " + this.name;
}
}
Next: Abstract classes
Article author: Arthur Isaev