Code Logo

Implement Interface with Class

Published at25 Jul 2026
TypeScript Classes & OOP Medium 0 views
Like0

Write a TypeScript interface Shape with an area() method signature, then implement it with a Circle class. The implements keyword ensures the class satisfies the interface contract. TypeScript will report a compile error if the class is missing any interface members.

The implements keyword in TypeScript allows a class to declare that it conforms to an interface. Unlike extends which inherits implementation, implements only checks structural compatibility. A class can implement multiple interfaces: class MyClass implements IFoo, IBar. The compiler verifies that all required properties and methods exist with correct types.

Interfaces in TypeScript are purely a compile-time construct. They have no runtime representation. When a class implements an interface, the compiler checks the types but no metadata is emitted. This is different from languages like Java where implements has runtime effects.

Time complexity is O(1) for area calculation. Space complexity is O(1). The interface is erased at compile time with no runtime overhead.

Edge cases include implementing interfaces with optional members, multiple interfaces with conflicting members, and ensuring method signatures match exactly including parameter types and return types.

Example Input & Output

Example 1
Input
0
Output
0
Explanation

Zero radius

Example 2
Input
1
Output
3.14
Explanation

PI*1^2 ≈ 3.14

Example 3
Input
3
Output
28.27
Explanation

PI*9 ≈ 28.27

Example 4
Input
5
Output
78.54
Explanation

PI*25 ≈ 78.54

Example 5
Input
2
Output
12.57
Explanation

PI*4 ≈ 12.57

Algorithm Flow

Recommendation Algorithm Flow for Implement Interface with Class
Recommendation Algorithm Flow for Implement Interface with Class

Solution Approach

interface Shape {
  area(): number;
}

class Circle implements Shape {
  constructor(public radius: number) {}
  area(): number {
    return Math.PI * this.radius * this.radius;
  }
}

function solution(r: number): number {
  var c = new Circle(r);
  return Math.round(c.area() * 100) / 100;
}

Best Answers

typescript - Approach 1
interface Shape {
  area(): number;
}

class Circle implements Shape {
  constructor(public radius: number) {}
  area(): number {
    return Math.PI * this.radius * this.radius;
  }
}

function solution(r: number): number {
  var c = new Circle(r);
  return Math.round(c.area() * 100) / 100;
}