Home > Mobile >  Undefined property on an object
Undefined property on an object

Time:02-08

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:

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.

CodePudding user response:

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

let limit = dataObj?.pageLimit ?? 1000;

CodePudding user response:

Here is the solution:

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

  •  Tags:  
  • Related