Class with Typed Properties
Write a TypeScript class Rectangle with typed width and height properties (both number), a constructor that initializes them, and an area() method that returns the area. TypeScript classes add type annotations to JavaScript class syntax.
TypeScript classes combine JavaScript's class syntax with type annotations. Properties can be declared with types: width: number. The constructor uses parameter property syntax: constructor(public width: number, public height: number) which automatically creates and initializes properties. This reduces boilerplate compared to manually assigning this.width = width.
TypeScript also supports access modifiers (public, private, protected), readonly properties, static members, abstract classes, and implements clauses for interfaces. These features make TypeScript classes more expressive than plain JavaScript classes while compiling down to standard ES6 class syntax.
Time complexity is O(1) for area calculation. Space complexity is O(1) for the class instance. The type annotations are erased at compile time with no runtime overhead.
Edge cases include zero or negative dimensions (area can be zero or positive), very large numbers, and ensuring the method returns a number type that matches the type annotation.
Example Input & Output
Zero width
7*3=21
3*4=12
10*10=100
Square
Algorithm Flow

Solution Approach
Best Answers
class Rectangle {
constructor(public width: number, public height: number) {}
area(): number {
return this.width * this.height;
}
}
function solution(w: number, h: number): number {
var r = new Rectangle(w, h);
return r.area();
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
