Available in TypeScript 2.1 there is now the possibility to set partial properties values of objects, making it very easy to initialize new objects.
I had the problem before that whenever I wanted to create a new object and also initilize a new object, I had to set my values in the constructor, all my values.
export class Example{
text: string;
constructor(init?: Partial<Example>) {
// This will set values for each properties that can be found
Object.assign(this, init);
}
}
Now with the above code I can run a map function on an array and use the object itself as a constructor parameter. Like below.
// array filled with data is coming from firestore in this example
const ExamplesObs = <Observable<Example>>this.db.doc(`example/mycoolexampleDoc`).valueChanges().pipe(
map((fbl: Example) => {
let ex: Example = new Example(ex);
return ex
})
// Subscribe to the Observable etc...
The Observable will return an initialized object of the Example class. Now I am using firestore to get the data (in json format) and what will come back is simply just the json structure so this would be a great way to put the data into the real object with the help of a constructor with Partial.