TypeScript code defining a type for the getBoundingClientRect method that can be called on either a window or an HTMLElement variable

I am currently working on implementing a feature where users can define the viewport of an HTML element. If no viewport is specified, it should default to the window. However, I need to retrieve the getBoundingClientRect() property of the element if it's not the window. Here is my current approach: I have defined the variable as HTMLElement | Window, but encounter an error when trying to access the property in the following code snippet:

if (opts.viewport === window) {
  viewportHeight = window.innerHeight
  viewportWidth = window.innerWidth
} else {
  const viewportRect = opts.viewport.getBoundingClientRect()
  viewportHeight = viewportRect.height
  viewportWidth = viewportRect.width
}

The error message that I receive is:

Property 'getBoundingClientRect' does not exist on type 'Window | HTMLElement'.
  Property 'getBoundingClientRect' does not exist on type 'Window'.

I would like to know how I can properly type this scenario using TypeScript.

Answer №1

If you want to specify the type in your else block when using TypeScript, you can do so like this:



if (opts.viewport === window) {
    viewportHeight = window.innerHeight;
    viewportWidth = window.innerWidth;
} else {
    const viewportRect = (opts.viewport as HTMLElement).getBoundingClientRect();
    viewportHeight = viewportRect.height;
    viewportWidth = viewportRect.width;
}

Another option is to create and utilize a type guard:

const isHTMLElement = (target: Window | HTMLElement): target is HTMLElement =>
    (target as HTMLElement).getBoundingClientRect() !== undefined;

if (isHTMLElement(opts.viewport)) {
    const viewportRect = opts.viewport.getBoundingClientRect();
    viewportHeight = viewportRect.height;
    viewportWidth = viewportRect.width;
} else {
    viewportHeight = window.innerHeight;
    viewportWidth = window.innerWidth;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Resolve Redux-Firestore issue #45: Possible Solutions?

I'm facing an issue where deleting a document from Firestore results in my Redux store showing it as null instead of removing it. Even though the document is deleted in Firestore, this inconsistency causes frontend issues because my .map functions can ...

Transferring files from one azure blob container to another

I am currently utilizing the @azure/storage-blob package to manage files within Azure. Within the same Azure storage account, I have two storage containers - one for source files and the other for destination files. My objective is to copy a file from th ...

How can I successfully submit a page without refreshing using OTP?

When I fill in the information and try to send the OTP, the website reloads. Here is the link to the website: If you fill in the information and click on "Request verification code," you will understand what I mean. What I attempted was: $(function () { ...

Creating a completely dynamic button in Angular 6: A step-by-step guide

I have been working on creating dynamic components for my application, allowing them to be reusable in different parts of the program. At this point, I have successfully developed text inputs that can be dynamically added and customized using the component ...

Should I convert to an image or utilize the canvas?

I'm debating whether it's more efficient to convert a canvas drawing into an image before inserting it into the DOM, or if it's better to simply add the canvas itself. My method involves utilizing canvas to generate the image. ...

Why isn't my Vue.js3 table being updated after using axios asynchronously?

After conducting my research, it appears that I have followed all the correct steps. However, I am unable to identify why my table is not updating. Initially, I create a new company and proceed to the overview, but nothing is being displayed. While checki ...

Adding methods to a constructor's prototype in JavaScript without explicitly declaring them

In the book Crockford's JavaScript: The Good Parts, there is a code snippet that demonstrates how to enhance the Function prototype: Function.prototype.method = function (name, func) { this.prototype[name] = func; return this; }; Crockford elabo ...

No data was submitted with the HTML form post request in the formData object

I am encountering an issue while trying to use the formdata object to send form data to my server. The formdata object appears blank when attempting to send the data, and it only prints out "{}". I have updated jQuery to version 11.1 which is supposed to s ...

Looking to Add Dynamic Website Embed Link?

When a user arrives at the website and the Current Top URL is "https://website.com/?code=https://webbbb.com", I need to dynamically set the iframe URL to "https://webbbb.com" for embedding purposes. This way, I can automatically link my complete other web ...

What is the best way to display API error messages to the user?

When a user tries to upload a file that is not an image, I need to display the error message returned from a REST API. The JSON response received from the API will look something like this: { "publicError": "Could not be uploaded, it is not an image! ...

Error: Attempting to access the 'SearchBox' property of an undefined variable is not allowed

I have been working on a Google Maps code that displays both public and private schools with different markers for each category. However, when running the code, I encountered an error specifically on this line of code: var searchBox = new google.maps.pl ...

When async is set to true in an Ajax call, the response may come

I recently developed a function that works perfectly fine when the async option is set to false. However, I am now looking to achieve the same functionality and return value but with async set to true. function Call(param, proc) { var url = "../../ ...

Securing JWT signatures for both server-side and client-side environments

I am looking to authenticate Salesforce's OAuth 2.0 JWT Bearer Flow using both node.js and a Browser. I have generated a public key and a private key on Windows by running the following command. openssl req -x509 -sha256 -nodes -days 36500 -newkey r ...

Build a complete React application with full-stack development using the WAMP stack on your local machine

Is there a way to set up a local development environment with React on the front-end and a full-stack server like WAMP? The goal here is to: Utilize the default React Create App setup without ejecting scripts Make AJAX requests to PHP files that interac ...

Explore a vast array of items in a collection

I have a massive collection of various objects that I need to sift through. With over 60,000 elements, the search operation can sometimes be painfully slow. One typical object in this array has the following structure: { "title": "title" "company": ...

Multiple 'keydown' events are accumulating with Ajax activated

When the search field is focused, I am loading JSON into the browser and then iterating over the JSON objects to find real-time results 'on keydown'. The issue I'm encountering is detailed in the console after the initial block of code Aja ...

Encountering a syntax error while transferring information from Ajax to PHP

I am currently experiencing an issue with my Ajax and PHP setup. Upon checking the browser console, I encountered the following error message: The following error occured: parsererror SyntaxError: Unexpected token <. Despite multiple attempts at debugg ...

Is it true that event.stopPropagation does not function for pseudoelements?

I am facing an issue with event handling in my ul element. The ul has three li children elements, and the ul itself has a useCapture event handler for click. In the click event handler, I successfully stop the event using event.stopPropagation(), and every ...

When a new marker is clicked on Google Maps, the previous Infowindow will automatically close

Here are some specific locations to consider: var places = [{ "id": 1, "ReferenceNumber": "52525252525", "Address" : "School" , "Latitude": "21.585486", "Longitude": & ...

Retrieving, storing, and utilizing JSON variables in Express

I've been struggling to grasp the concept of accessing and processing data using different HTTP methods like get, put, post. Currently, I have managed to retrieve JSON data and store it in a global variable. var pokemonsData; fetch('https://raw ...