Implicit Implementation And Object Shape

suggest change

TypeScript supports interfaces, but the compiler outputs JavaScript, which doesn’t. Therefore, interfaces are effectively lost in the compile step. This is why type checking on interfaces relies on the shape of the object - meaning whether the object supports the fields and functions on the interface - and not on whether the interface is actually implemented or not.

interface IKickable {
  kick(distance: number): void;
}
class Ball {
  kick(distance: number): void {
    console.log("Kicked", distance, "meters!");
  }
}
let kickable: IKickable = new Ball();
kickable.kick(40);

So even if Ball doesn’t explicitly implement IKickable, a Ball instance may be assigned to (and manipulated as) an IKickable, even when the type is specified.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents