Code Logo

Class with Typed Properties

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

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

Example 1
Input
0,10
Output
0
Explanation

Zero width

Example 2
Input
7,3
Output
21
Explanation

7*3=21

Example 3
Input
3,4
Output
12
Explanation

3*4=12

Example 4
Input
10,10
Output
100
Explanation

10*10=100

Example 5
Input
5,5
Output
25
Explanation

Square

Algorithm Flow

Recommendation Algorithm Flow for Class with Typed Properties
Recommendation Algorithm Flow for Class with Typed Properties

Solution Approach

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();
}

Best Answers

typescript - Approach 1
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();
}