DEV Community

Cover image for Interfaces in Typescript
Nico Braun
Nico Braun

Posted on • Updated on

Interfaces in Typescript

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
}
Enter fullscreen mode Exit fullscreen mode

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
  }
}
Enter fullscreen mode Exit fullscreen mode

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
  }
}
Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed this post and that you will start playing with typescript. It is amazing.

Thank you.

Discussion (0)