繁体   English   中英

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

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

这是界面的样子

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

这是我的元组

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

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

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

错误信息 :

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

谢谢您的帮助

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

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

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

如果只需要一个元素(即长度为1的元组)。 然后将其用于linkedDoctorShort类型,并相应地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,
}; 

将界面更改为:

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

但是我不是内联打字的忠实粉丝。 我喜欢更简洁的语法,例如:

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

export interface Patient {
  doctors: Doctor[];
}

尽管您遇到错误,但建议是明确的类型定义。

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

就像@jpavel所说的。 那么您可以利用Typescript的优势。

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

你不会错过的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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