Type casting alone does not allow for achieving this functionality. When you cast an object as Product
, you are essentially telling the compiler, "Treat this as a Product even though it may not possess all the attributes of a Product".
If default values are needed, a constructor must be added to the class, like so:
export class Product {
price: number;
label: string;
details: string;
constructor(obj: {price?: number, label?: string, details?: string}) {
this.price = obj.price || 20;
this.label = obj.label || "No name";
this.details = obj.details || "No description";
}
}
This way, passing a partial configuration object will automatically set the other default values.
let laptop = new Product({label: 'Laptop'});
// {label: 'Laptop', price: 20, details: 'No description'}
Now, laptop
is inherently of type
Product</code without needing explicit casting. </p>
<p>An easier approach to typing your constructor parameter is by using the <code>Partial
type.
type Partial<T> = {
[P in keyof T]?: T[P];
}
Thus, your constructor parameter would appear as
constructor(obj: Partial<Product>)
To delve deeper into type assertions (or type casting), refer to the 'Type Assertions' section within this article: https://www.typescriptlang.org/docs/handbook/basic-types.html.