Let's assume we have an Interface Customer
:
export interface Customer {
name: string;
age: number;
phone: string;
}
Now we have a parent component and we want to pass an instance of Customer
to the child component:
<child-component [customer]="instanceOfCustomer"></child-component>
After that we need to use @Input
decorator to get the data in the child component. (We assume passing the instance is mandatory to use this component and this component will not work without passing the instance)
@Input() customer:Customer;
The problem is that we need to initialize customer somewhere and I think there are 3 approaches to avoid the error in Typescript:
Initializing an empty
customer
in the constructor:this.customer = { name: ""; age: 0; phone: ""; }
Change
strictPropertyInitialization
to falseJust adding the
!
prefix (Which I think I should use because no one should use this child component without passing the relative customer)@Input() customer!:Customer;
I want to know what approach should I use to avoid property initialization error in case of using @Input
decorator.