TypeScript from zero: an interface is a method list
An interface lists the methods a function needs. Labeller asks for label. Item has label. show prints latte $4.50.
Arthur is one of GoByte's characters. This post was drafted by AI agents in Arthur's voice, then fact checked, run and edited by the GoByte team.
show needs label. It does not need the price field, and it does not need the class name. An interface lists the methods. A class that has those methods fits, and the function can take the interface instead of the class. A discount line with its own label can use the same receipt function.
The interface is the methods you may call#
An interface lists the operations a caller needs. Labeller lists label(): string. The class says implements Labeller, and the checker confirms the method exists with a compatible signature. show accepts a Labeller, so its body can call label and cannot use cents. A different class that implements the same interface can be passed in without changing show. The interface is erased at runtime. The method call that remains is an ordinary JavaScript call.
- Itemlabel()latte $4.50
- missing labeldoes not compile
interface Labeller {
label(): string;
}
class Item implements Labeller {
name: string;
cents: number;
constructor(name: string, cents: number) {
this.name = name;
this.cents = cents;
}
label(): string {
const frac = String(this.cents % 100).padStart(2, "0");
return this.name + " $" + Math.floor(this.cents / 100) + "." + frac;
}
}
function show(item: Labeller): void {
console.log(item.label());
}
show(new Item("latte", 450));
latte $4.50
implements checks the method list#
Labeller says label takes no arguments and returns a string. class Item implements Labeller asks the checker to prove Item has that method. show takes a Labeller and calls label. new Item("latte", 450) is an Item, which is a Labeller, so the call is legal. The print is latte $4.50.
A second class with its own label can be passed to show without editing show. That is why the parameter type is the interface and not Item. show depends on the behavior.
Do not list fields the caller never reads#
show never reads cents. Putting cents: number on Labeller would force every labeller to have a price, including ones that label a note or a person. List the method you call. The class keeps the fields the method needs, and the caller stays on the method.
Your product here? Partner with us
Back to topDiscussion
No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines
Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.