Factory
Let's assume that we have a User
class with two private variables: lastName:string
and firstName:string
. In addition, this simple class proposes that the hello
method prints "Hi I am", this.firstName, this.lastName
:
class User{ constructor(private lastName:string, private firstName:string){ } hello(){ console.log("Hi I am", this.firstName, this.lastName); } }
Now, consider that we receive users through a JSON API. It will more than likely look something like this:
[{"lastName":"Nayrolles","firstName":"Mathieu"}...].
With the following snippet, we can create a User
:
let userFromJSONAPI: User = JSON.parse('[{"lastName":"Nayrolles","firstName":"Mathieu"}]')[0];
Up until now, the TypeScript compiler hasn't complained, and it executes smoothly. It works because the parse method returns any
(for example, the TypeScript equivalent of the Java object). Sure enough, we can convert the any into User
. However, userFromJSONAPI.hello();
will yield the following:
json...