How to check if a point is inside a rectangle in TypeScript

2 Answers

0 votes
class Point {
    x: number;
    y: number;

    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
}

class Rectangle {
    topLeft: Point;
    bottomRight: Point;

    constructor(topLeft: Point, bottomRight: Point) {
        this.topLeft = topLeft;
        this.bottomRight = bottomRight;
    }
}

function isPointInsideRectangle(p: Point, rect: Rectangle): boolean {
    return p.x >= rect.topLeft.x && p.x <= rect.bottomRight.x &&
           p.y >= rect.topLeft.y && p.y <= rect.bottomRight.y;
}

const rect: Rectangle = new Rectangle(new Point(0.0, 0.0), new Point(7.0, 7.0));
const p: Point = new Point(3.0, 2.0);

if (isPointInsideRectangle(p, rect)) {
    console.log("The point is inside the rectangle.");
} else {
    console.log("The point is outside the rectangle.");
}


     
/*
run:
     
"The point is inside the rectangle." 
     
*/

 



answered Jun 22, 2025 by avibootz
0 votes
type Point = { x: number; y: number };
type Rect = { x1: number; y1: number; x2: number; y2: number };

const x1 = 0.0, y1 = 0.0;
const x2 = 7.0, y2 = 7.0;
const x = 3.0, y = 2.0;

const pointInRect = (rect: Rect, point: Point): boolean => {
  return point.x >= rect.x1 && point.x <= rect.x2 &&
         point.y >= rect.y1 && point.y <= rect.y2;
};

const rect: Rect = { x1, y1, x2, y2 };
const point: Point = { x, y };

if (pointInRect(rect, point)) {
  console.log("The point is inside the rectangle.");
} else {
  console.log("The point is outside the rectangle.");
}


     
/*
run:
     
"The point is inside the rectangle." 
     
*/

 



answered Jun 22, 2025 by avibootz
...