Factory method
Let's assume that we have a User
class with two private variables: lastName:string
and firstName:string
. In addition, this simple class proposes the hello
method that 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'll 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];
Until now, the TypeScript compiler doesn't complain, 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...