Factory pattern
Let's assume that we have a User
class with two private variables: lastName:string
and firstName:string
. Also, this simple class proposes the method hello 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. Most likely, it will 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
(that is, the TypeScript equivalent of the Java Object). Sure enough, we can convert the any
into User
. However, userFromJSONAPI.hello()
; will yield:
json.ts:19 userFromJSONAPI.hello...