Issue
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.
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;
Answered By - Terry
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.