简体   繁体   中英

Property '0' is missing in type 'any[]' but required in type '[{ id: string; gp: boolean; }]

Here's what the interface look like

 export interface Patient {
    doctors: [{
      id: null,
      gp: null,
     }]
  }

Here's my tuple

  linkedDoctorShort: Array<any> = []; // will contain only the ID and GP 

I tried some solutions that I had found on StackOverflow, but I still got the same error, especially when I want to save all the information:

  onSave() {
    const patientInfo: Patient = {
    doctors: this.linkedDoctorShort,
  }; 

Error message :

Property '0' is missing in type 'any[]' but required in type '[{ id: string; gp: boolean; }]'.

Thank you for your help

linkedDoctorShort: Array<any> = []; is not a tuple. It is an array initialized with an empty array.

If you want this to be an array ( doctors can have any number of elements) use an array type in the interface

 export interface Patient {
    doctors: Array<{
      id: null,
      gp: null,
     }>
  }

If you want only a single element (ie a tuple of length one). Then use that in the type of linkedDoctorShort and initialize it accordingly:

export interface Patient {
    doctors: [{
        id: null,
        gp: null, // are you sure these can only be null ? I think you mean soemthing like string | null
    }]
}

let linkedDoctorShort: [any] = [{ id: null, gp: null }]; //  Or better yes let linkedDoctorShort: [Patient['doctors'][0]] to keep type safety 

const patientInfo: Patient = {
    doctors: this.linkedDoctorShort,
}; 

Change your interface to:

export interface Patient {
  doctors: Array<{id: string;gp: boolean;}>;
}

But I'm not a huge fan of inline typing. I prefer a cleaner syntax, like:

export interface Doctor {
  id: string;
  gp: boolean;
}

export interface Patient {
  doctors: Doctor[];
}

despite the error you encounter, suggestion is clear type definition.

export interface Doctor {
    id: string | number;
    gp: boolean;    
}
export interface Patient {
    doctors: Doctor[];
}

Just as @jpavel said. then you can use the advantage of Typescript.

const linkedDoctorShort:Doctor[] = [];
onSave() {
    const patientInfo: Patient = {
    doctors: this.linkedDoctorShort,
}; 

you won't miss it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM