Casting
Cast (Aka. clone) allow to cast any object to class instance
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 isfalse
)
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.ts
export 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.ts
import { cast } from "@sugoi/core";
const casted = cast(Post,{title:"wow",body:"Much body"});
// in that case creation and owner won't initialize
casted.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.ts
export 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.ts
import { cast } from "@sugoi/core";
const casted = cast(Post,{title:"wow",body:"Much body"});
// in that case creation and owner won't initialize
casted.print(); => "wow - Much body - 11/11"
Last modified 4yr ago