类型“any[]”中缺少属性“0”,但类型“[{ id: string; gp:布尔值;}]

M.E*_*Ela 2 javascript typescript

这是界面的样子

 export interface Patient {
    doctors: [{
      id: null,
      gp: null,
     }]
  }
Run Code Online (Sandbox Code Playgroud)

这是我的元组

  linkedDoctorShort: Array<any> = []; // will contain only the ID and GP 
Run Code Online (Sandbox Code Playgroud)

我尝试了我在 StackOverflow 上找到的一些解决方案,但仍然出现相同的错误,尤其是当我想保存所有信息时:

  onSave() {
    const patientInfo: Patient = {
    doctors: this.linkedDoctorShort,
  }; 
Run Code Online (Sandbox Code Playgroud)

错误信息 :

类型“any[]”中缺少属性“0”,但类型“[{ id: string; gp:布尔值;}]'。

感谢您的帮助

Tit*_*mir 7

linkedDoctorShort: Array<any> = [];不是元组。它是一个用空数组初始化的数组。

如果您希望这是一个数组(doctors可以有任意数量的元素),请在界面中使用数组类型

 export interface Patient {
    doctors: Array<{
      id: null,
      gp: null,
     }>
  }
Run Code Online (Sandbox Code Playgroud)

如果你只想要一个元素(即长度为一的元组)。然后在类型中 linkedDoctorShort使用它并相应地初始化它:

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,
}; 
Run Code Online (Sandbox Code Playgroud)