When I first run ionic serve, I get a page or errors along the lines of:
Property ‘user’ does not exist on type ‘Object’
If I re-save any file, ionic reloads and all the errors disappear. Is this normal, or do I have something wrong?
This is always on a response variable which is returned from an http call via rxjs .toPromise().
The res variable is just declared like:
.toPromise()
.then(res => {
console.log(res.user);
});
So I haven’t declared a type for res as it’s just created when the call comes back.
This doesn’t make sense. 99.9% of the time it’s best to declare a type. Either do it by taking advantage of the generic method you’re calling, if you’re calling one, or do it manually:
(res: TypeGoesHere) => console.log(res)
But maybe the biggest thing is: if you’re calling your variable res, you’re already typing wrong. Call it whatever you’re expecting it to be, for example userProfile.
OK thanks.
So are you saying I can’t just define this as a generic <object>
type - because I’ll still encounter this error. Instead I need to define a class, which has the properties defined, then make the return variable of that type?
But also why do the errors only present themselves when I first run ionic serve? Is there a linting or something that only runs on the initial load?
That’s the standard prescription. I use interfaces and enums, not classes, because I try to keep variables immutable. But however you do it, it’s good style to give everything a type.
Also, if you built for production, you wouldn’t get past the compile. Ionic serve is more forgiving than the Angular compiler.
Ah I see, will check out interfaces. Thanks for taking the time, much appreciated.