Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Undefined property on an object

I have a Typescript project in which I am reassigning variables depending on the value that the object contains.

What I am trying to do is define a variable from a property of the object, instead, if this property does not exist, a default value is established.

This is my Object:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

interface InsParams {
  host?: string,
  country?: string,
  pageLimit?: number,
  pageOffset?: number,
  pageToken?: string
}

let dataObj: InsParams;

This is the variable I’m creating:

let limit: number = dataObj.pageLimit ? dataObj.pageLimit : 1000

This is the error it shows:

Error: Cannot read properties of undefined

My problem: I need if the property does not exist to assign another value to the limit variable, but it shows an error.

>Solution :

Your issue comes from dataObj being potentially undefined. In this case, you can use optional chaining + null coalescing operator:

let limit = dataObj?.pageLimit ?? 1000;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading