The compiler allows you to cast the object returned from JSON.parse
to a class because of TypeScript's structural subtyping principle, as explained in this documentation. This means that even though you don't have an instance of an actual Employee
class, the object you receive has the same properties.
Here's a simpler example to illustrate this:
class A {
constructor(public str: string, public num: number) {}
}
function logA(a: A) {
console.log(`A instance with str: "${ a.str }" and num: ${ a.num }`);
}
let a1 = { str: "string", num: 0, boo: true };
let a2 = new A("stirng", 0);
logA(a1);
logA(a2);
(code in playground)
In this scenario, there are no errors because a1
satisfies type
A</code by having all the necessary properties. The <code>logA
function can be called without runtime errors, even if it receives an object that is not a direct instance of
A</code, as long as it contains the same properties.</p>
<p>However, when methods are introduced to classes, complications arise:</p>
<pre><code>class A {
constructor(public str: string, public num: number) { }
multiplyBy(x: number): number {
return this.num * x;
}
}
// This will not compile:
let a1 = { str: "string", num: 0, boo: true } as A;
// This will compile but lead to a runtime error:
let a2 = { str: "string", num: 0 } as A;
// Resulting in a runtime error:
a2.multiplyBy(4); // Error: Uncaught TypeError: a2.multiplyBy is not a function
(code in playground)
Edit
The following code snippet works perfectly:
const employeeString = '{"department":"<anystring>","typeOfEmployee":"<anystring>","firstname":"<anystring>","lastname":"<anystring>","birthdate":"<anydate>","maxWorkHours":0,"username":"<anystring>","permissions":"<anystring>","lastUpdate":"<anydate>"}';
let employee1 = JSON.parse(employeeString);
console.log(employee1);
(code in playground)
If you attempt to apply JSON.parse
on an object instead of a string like in the following example:
let e = {
"department": "<anystring>",
"typeOfEmployee": "<anystring>",
"firstname": "<anystring>",
"lastname": "<anystring>",
"birthdate": "<anydate>",
"maxWorkHours": 3,
"username": "<anystring>",
"permissions": "<anystring>",
"lastUpdate": "<anydate>"
}
let employee2 = JSON.parse(e);
You will encounter an error because e
is not a string but an object. If your data is already in object form, there is no need to utilize JSON.parse
.
To create an instance of a class rather than just having an object with similar properties:
let e = new Employee();
Object.assign(e, {
"department": "<anystring>",
"typeOfEmployee": "<anystring>",
"firstname": "<anystring>",
"lastname": "<anystring>",
"birthdate": "<anydate>",
"maxWorkHours": 3,
"username": "<anystring>",
"permissions": "<anystring>",
"lastUpdate": "<anydate>"
});