Currently learning angular. Cannot use input as an argument because it has the optional marker?

Issue

I have a button component that takes an "id" parameter passed down by its parent component. In this.crudService.DeletePost(this.id).subscribe( data => console.log(data)), why am I getting an error of "Argument of type ‘string | undefined’ is not assignable to parameter of type ‘string’.
[1] Type ‘undefined’ is not assignable to type ‘string’."

import { Component, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CrudService } from 'src/app/service/crud.service';

@Component({
  selector: 'app-kehbab-menu',
  templateUrl: './kehbab-menu.component.html',
  styleUrls: ['./kehbab-menu.component.css']
})
export class KehbabMenuComponent implements OnInit {
  @Input() id?: string;

  constructor(private router: Router, private crudService: CrudService) { }

  ngOnInit( ): void {
  }

  async removePost() {

    //delete -- this is where I get the error saying this.id is undefined but I can console log it and it shows the id.
    await this.crudService.DeletePost(this.id).subscribe( data => console.log(data));

    //refresh home
    await this.router.navigateByUrl('/search', { skipLocationChange: true }).then(() => {
      this.router.navigate(['/home']);
     }); 
  }

}

Solution

why am I getting an error of "Argument of type ‘string | undefined’ is not assignable to parameter of type ‘string’.

You are simply being warned of a potential problem in your code. You have defined @Input() id?: string;. This means that id is either a string or undefined. You then pass this variable to this.crudService.DeletePost(this.id) which I believe accepts a string. You are therefore trying to assign string | undefined to string.

To solve this you have a number of ways, a simple one is simply a check using if

  async removePost() {
    if (this.id) {
          //delete -- this is where I get the error saying this.id is undefined but I can console log it and it shows the id.
    await this.crudService.DeletePost(this.id).subscribe( data => console.log(data));

    //refresh home
    await this.router.navigateByUrl('/search', { skipLocationChange: true }).then(() => {
      this.router.navigate(['/home']);
     });
    } 
  }

You can also use non-null operator this.crudService.DeletePost(this.id!). Note the !

Another option is typecasting this.crudService.DeletePost(this.id as string)

You can also just define your property as a string with a default value. You can then check if the property is '0' in the service

@Input() id = '0';

Answered By – Owen Kelvin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published