I find the behavior of the Typescript compiler quite perplexing in relation to this code. I am using JSON.parse to populate a class instance from another class instance's output of stringify
.
It seems like the return value of JSON.parse is simply a regular object. When I pass this object to a load method, it functions properly, but the compiler throws an error saying that it can't locate the property. Strangely, if the object is re-parsed (i.e. JSON.parse(JSON.stringify(obj))
) within the load method, there are no longer any complaints from the compiler. What exactly makes one instance "unknown" to the compiler while the other is recognized? Is there truly a distinction between these two instances or is it some sort of type checking hiccup?
class Address {
street = "12 Main Street"
city = "Fooville"
load(obj: object) {
this.hello();
this.street = obj.street; // <-- "Property street does not exist on type object
this.city = obj.city; // <-- "Property city doe snot exist on type object
this.hello();
let parseObj = JSON.parse(JSON.stringify(obj));
this.street = parseObj.street; // <-- no complaints
this.city = parseObj.city; // <-- no complaints
console.log(parseObj.constructor.name);
console.log(obj.constructor.name);
}
hello() {
console.log(`My address is ${this.street}, ${this.city}`);
}
}
let foo = new Address();
foo.city="Raleigh"
let jstring = JSON.stringify(foo);
let goo = new Address();
let jparse = JSON.parse(jstring);
goo.load(jparse);
goo.city = "Denver"
goo.hello();
foo.hello();
console out:
My address is 12 Main Street, Fooville
My address is 12 Main Street, Raleigh
Object
Object
My address is 12 Main Street, Denver
My address is 12 Main Street, Raleigh