I have an object like so…
let myObj = {
name: 'John',
address: {
lineA: 'Address line 1',
lineB: 'Address line 2'
}
}
I’m pushing this object to a new page and retrieving it through navParams
which all works fine.
If I console.log(myObj);
after retrieving it through navParams
it logs the object as expect, although if I try to console.log(myObj.address);
I receive an error saying that the Property 'address' does not exist on the type 'Object'
.
I can use this syntax to get it to work: console.log(myObj['address']);
but there must be a way to do this using dot notation.
Thanks for any help.
I solved this by specifying its type to any
instead of what I had it as which was Object
.
Example Before
myObj: Object;
Example After:
myObj: any;
The above “solution” is bad. any
should not be abused in situations like this. The right thing to do is to define interfaces for all your types:
interface Address {
lineA: string;
lineB?: string;
}
interface Person {
name: string;
address: Address;
}
myObj: Person;
Not only does this protect you from typos in a way that any
cannot, it also makes your code self-documenting and much more readable.
1 Like
This is much better thanks, I didn’t know about this.
I assumed that lineB
is optional in addresses; that is what the ?
does. More information here.
1 Like