Angular: how to fix this Type 'Customer | undefined 'is not assignable to type' Customer '
I am experiencing this error. This is code:
...
export class ListCustomersComponent implements OnInit {
customers: Array<Customer> = [];
showCustomer?: Customer;
isSelected: boolean = false;
deletedCustomer?: Customer;
returnedMessage?: string;
constructor(private customerService: CustomerService,
private messageService: MessageService) { }
updateCustomer() {
this.customerService.updateCustomer(this.showCustomer!)
.subscribe((message: Message) => {
console.log(message);
// update customers list
this.customers.map(x => {
if(x.id == this.showCustomer!.id){
ERROR------> x = this.showCustomer;
}
});
}
The error is in updateCustomer() to the line x = this.showCustomer;. How can I fix it? Thank you all
Typescript is giving a warning that the value may be undefined. An exclamation point ignores that warning. This is fine if your logic ensures that there will be a value. If there isn't a value x will be set to undefined.
To ignore the warning for this case you have to add an exclamation mark for the x = this.showCustomer
statement. By using !
typescript marks it as present.
this.customerService.updateCustomer(this.showCustomer!)
.subscribe((message: Message) => {
console.log(message);
// update customers list
this.customers.map(x => {
if(x.id == this.showCustomer!.id){
x = this.showCustomer!; // Added ! after showCustomer
}
});
Explanation !
in docs