Sandeep Thomas
Sandeep Thomas

Reputation: 4759

Object is possibly 'undefined' When trying to get width of html element using JQUERY in Angular

I am trying to use JSPDF to convert a table into PDF with multiple pages. So as part of that I am trying to get width and height of my html

var HTML_Width = $("#pdfTable").width();
var HTML_Height = $("#pdfTable").height();
var top_left_margin = 15;
var PDF_Width:number = HTML_Width+(top_left_margin*2);

But in above snippet HTML_width shows Object is possible undefined.

enter image description here

How to resolve that

Upvotes: 1

Views: 481

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075239

If there is no element with the id pdfTable, jQuery's $() will return an empty jQuery object, and calls to width and height on that empty object will return undefined. As a result, their return type is number | undefined.

If you know (or rather, expect) that the element will exist, you can document that in the code and reassure TypeScript by throwing an error if that expectation is not met, like this:

var HTML_Width = $("#pdfTable").width();
var HTML_Height = $("#pdfTable").height();
if (typeof HTML_Width === "undefined" || typeof HTML_Height === "undefined") {
    throw new Error(`Expected element with id="pdfTable"`);
}
var top_left_margin = 15;
var PDF_Width:number = HTML_Width+(top_left_margin*2);

You can also use a non-nullish assertion operator (a postfix !), but like all type assertions, it's best to avoid it in favor of guards like the above where possible. But for completeness:

// I don't recommend this
var HTML_Width = $("#pdfTable").width()!;
//                                     ^
var HTML_Height = $("#pdfTable").height()!;
//                                       ^
var top_left_margin = 15;
var PDF_Width:number = HTML_Width+(top_left_margin*2);

Upvotes: 2

Related Questions