Say I have Product
with three properties and their default values. How do I convert or cast {}
to Product
with respect to default value when there is no value in {}
?
export class Product{
Price:number=20;
Label:string="No name";
Details:string="no desc";
}
let laptop = {Label:'Laptop'} as Product;
//I would like to get this laptop ={Label:'Label',Price:20,Details:'no desc'}
This is not possible with type casting. All you're doing when you cast an object
as Product
is saying to the compiler, "This thing is a Product even though it doesn't have the same properties as a Product".If you want default values, you need to put a constructor on your class, like this:
Then you can pass any partial configuration object and the other default values will get set.
Now,
laptop
will automatically be of typeProduct
and you don't even have to cast it.Tip: you can use the
Partial
type to make typing your constructor parameter easier.Then your constructor parameter would look like
constructor(obj: Partial<Product>)
For more info on type assertions (aka type casting), read the 'Type Assertions' section of this article: https://www.typescriptlang.org/docs/handbook/basic-types.html.