When attempting to instantiate Typescript objects from JSON data received over HTTP, I began considering using the for..in
loop along with .hasOwnProperty()
:
class User {
private name: string;
private age: number;
constructor(data: JSON) {
console.log('on constructor\ndata', data);
for (var key in data) {
console.log('key:', key);
if (User.hasOwnProperty(key)) {
console.log('User has key:', key);
this[key] = data[key];
}
}
}
displayInfo(): string{
return JSON.stringify(this);
}
}
let button = document.createElement('button');
button.textContent = "Test";
button.onclick = () => {
try{
let json = JSON.parse('{"name": "Zorro","age": "24"}');
let usr = new User(json);
console.log(usr.displayInfo());
}catch (error){
alert(error);
}
}
document.body.appendChild(button);
However, when utilizing similar code in my project, it fails due to the fact that the compiled JS code does not recognize the private TS variables, resulting in hasOwnProperty
always returning false
.
Interestingly, when testing this code on the Typescript Playground, the console output shows unexpected behavior:
on constructor
data Object {name: "Zorro", age: "24"}
key: name
User has key: name
key: age
{"name":"Zorro"}
This unexpected behavior includes recognizing the first key and initializing the new User instance with the corresponding JSON value, but failing to do the same for the second key. Can anyone explain why this discrepancy occurs?