Cast allows to transform any object to class instance with all of the class functionalities including static methods and properties.
cast(classType, data, applyConstructor:boolean = false)
classInstance
- The typeof class we want to cast to.
data
- The data should be cast.
applyConstructor
- identify if constructor method should apply (default is false
)
​
Using cast can be done in two ways:
In that case the data will cast into class instance but constructor method will not apply, which means auto populated properties won't initialize.
post.class.tsexport class Post{title: string;body: string;creation: string = "11/11";owner: string;​constructor(owner:string){this.owner = owner;} print(){console.log(`${this.title} - ${this.body} - ${creation}`);}}
main.tsimport { cast } from "@sugoi/core";​const casted = cast(Post,{title:"wow",body:"Much body"});// in that case creation and owner won't initializecasted.print(); => "wow - Much body - undefined"
In that case the data will cast into class instance and constructor method will apply, which means auto populated properties will initialize.
post.class.tsexport class Post{title: string;body: string;creation: string = "11/11";owner: string;​constructor(owner:string){this.owner = owner;} print(){console.log(`${this.title} - ${this.body} - ${creation}`);}}
main.tsimport { cast } from "@sugoi/core";​const casted = cast(Post,{title:"wow",body:"Much body"});// in that case creation and owner won't initializecasted.print(); => "wow - Much body - 11/11"
​