【问题标题】:Property '0' is missing in type 'any[]' but required in type '[{ id: string; gp: boolean; }]类型“any[]”中缺少属性“0”,但类型“[{ id: string; gp:布尔值; }]
【发布时间】:2019-10-21 18:36:00
【问题描述】:

界面是这样的

 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:布尔值; }]'。

感谢您的帮助

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    将您的界面更改为:

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

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      如果您只想要一个元素(即长度为 1 的元组)。然后在 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,
      }; 
      

      【讨论】:

      • 我的坏接口实际上是 id: string 和 gp: boolean (编辑:谢谢我不再收​​到错误我不得不更改接口非常感谢)
      • @M.Ela 无论哪种方式,解决方案都是一样的,这对我来说看起来很奇怪:)
      【解决方案3】:

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

      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,
      }; 
      

      你不会错过的

      【讨论】:

        猜你喜欢
        • 2020-05-18
        • 2021-10-02
        • 1970-01-01
        • 2019-04-28
        • 2018-03-03
        • 2019-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多