user11352561
user11352561

Reputation: 2647

Angular - error TS2532: Object is possibly 'undefined' in stateorigin.country.name

In my Aangular-12, I have this code:

API Json Response:

{
  "message": "States successfully Retrieved.",
  "error": false,
  "code": 200,
  "results": {
    "states": [
        {
            "id": 1,
            "country_id": 1,
            "name": "Cairo",
            "country": {
                "id": 1,
                "capital": "",
                "nationality": "Egyptian",
                "name": "Egypt",
            }
        }
    ]
  }
}

Interface:

export interface ICstate {
  id?: number;
  name: string;
  country_id: number;
  country?: [];
}

component:

stateorigin!: ICstate;

viewStateModal(row: any) {
  this.stateorigin = row;
}

HTML:

<a class="btn btn-primary btn-sm" (click)="viewStateModal(row)" data-toggle="modal" data-target="#viewStateModal">
                    View
                  </a>


<div class="modal fade" id="viewStateModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel"> State of Origin Details</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
      </div>

      <div class="modal-body" *ngIf="stateorigin != undefined">
        <div class="col-md-12">
          <div class="row">
            <div class="col-md-6">
              State of Origin: <strong>{{ stateorigin.name || 'N/A' }}</strong>
            </div>
            <div class="col-md-6">
              Country: <strong>{{ stateorigin.country.name || 'N/A' }}</strong>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal" (click)="hide()">Close</button>
      </div>
    </div>
  </div>

console.log(this.stateorigin);

gives:

Object
country: {id: 1, nationality: "Egyptian", name: "Egypt",}
country_id: 1
id: 1
name: "Cairo"

As I tried to view the stateorigin detail, I got this error:

error TS2532: Object is possibly 'undefined'.

100       Country: <strong>{{ stateorigin.country.name || 'N/A' }}</strong>

name is highlighted in stateorigin.country.name

A country has many stateorigin

How do I resolve this?

Thanks

Upvotes: 0

Views: 136

Answers (1)

depperm
depperm

Reputation: 10756

There seem to be two problems. First country is defined as an array but is being used as an object. Update the type:

country?: {id:number, name:string, capital?:string, nationality:string}

Then in the html because country is optional (and may not exist) you need to check before referencing (safe navigation operator)

stateorigin.country?.name || 'N/A'

Upvotes: 1

Related Questions