I'm grappling with a query about data types in TypeScript and Angular 2. I defined a class in TypeScript
export class product{
public id:number;
public name:string;
public status:boolean;
constructor(){}
}
and I initialize an instance of this class for system use.
private product:Product = new Product();
When I'm utilizing this product instance within TypeScript, it retains its product type. However, the issue arises when my backend is in PHP/Laravel. The backend sends me a JSON object when retrieving a product from the server, which I then assign to my product instance.
this.productService.getProductById(id).subscribe(result => {
this.product = result;
});
Upon assignment, the instance transitions from a product type to an object type. This realization dawns on me as I conduct console.log checks before and after the reassignment.
this.productService.getProductById(id).subscribe(result => {
console.log(this.product);
this.product = result;
console.log(this.product);
});
Console output:
Imagens {}
Object {id: 1, namme: "test", status: true…}
This presents an issue as I aim for strict data typing. Additionally, if the server response introduces a property not originally defined in the class, it gets added to the product instance. I seek a solution to ensure that my class instance only contains the predefined attributes.
Does anyone have insights on resolving this query?