This post is a ported version of the interface example from the Golang Documentation for Typescript.
Suppose, we are working with geometric shapes. We define an interface and define two methods, to get the area and the perimeter of the geometric shape.
interface Geometry {
area(): number
perim(): number
}
Next, we implement a class that represents a Rectangular, this class implements the Geometry interface and must therefore implement all functions listed in the Geometry interface.
class Rect implements Geometry {
constructor(private height: number, private width: number){}
area(): number {
return this.height*this.width
}
perim(): number {
return 2*this.height+2*this.width
}
}
We define another shape that implements the Geometry interface. While it has the same functions as the Rect, the implementation details are completely different.
class Circle implements Geometry {
constructor(private radius: number){}
area(): number {
return Math.PI*this.radius*this.radius
}
perim(): number {
return 2*Math.PI*this.radius
}
}
The interface does not care about implementation details, it only cares about the correct function signature being present.
function measure(g: Geometry): void {
console.log('geometry area', g.area())
console.log('geometry perimeter', g.perim())
}
const r = new Rect(2, 3)
const c = new Circle(1)
measure(r)
measure(c)
Here is another illustration. It is so powerful because we don't have to explicitly say this function takes a Rectangular or a Circle as argument. Instead, we can say this function takes anything that implements the Geometry interface, regardless of how this is achieved.
function sumArea(shapeA: Geometry, shapeB: Geometry): number {
return shapeA.area() + shapeB.area()
}
sumArea(new Circle(2), new Rect(1, 3))
I hope you enjoyed this post and that you will start playing with typescript. It is amazing.
Thank you.
Top comments (0)