Implement Interface with Class
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
Zero radius
PI*1^2 ≈ 3.14
PI*9 ≈ 28.27
PI*25 ≈ 78.54
PI*4 ≈ 12.57
Algorithm Flow
Solution Approach
Implement an interface in TypeScript using the implements keyword. Interfaces define the shape of an object with typed properties and methods. Classes implementing an interface must provide all its members.
A class can implement multiple interfaces. Interfaces can extend other interfaces. Unlike abstract classes, interfaces have no implementation or constructor.
Time O(1), Space O(1).
Best Answers
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;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
