【问题标题】:Typescript Errors in Function Pushing Objects to an Array将对象推送到数组的函数中的 Typescript 错误
【发布时间】:2017-07-04 20:49:18
【问题描述】:

我正在尝试将新对象推送到我的 Angular 2 应用程序中的数组中,但我遇到了一个问题(我怀疑这可能是 Typescript 类型的问题,尽管我不确定)。这就是我要推送的数组的样子:

locations = [
  { city: 'Los Angelas', postalCode: '90001', coordinates: 2321 },
  { city: 'New York', postalCode: '10001', coordinates: 3432 },
];

这是我用来将新邮政编码推送到数组的函数:

  addZipcode(event) {
    this.locations.push({ postalCode: this.newPostalCode });
    this.newPostalCode = '';
    this.addZipInput = false;
    event.preventDefault();
  }

我得到的错误是:这个函数是:

类型参数 '{ postalCode: any; }' 不可分配给参数 '{城市:字符串;邮政编码:字符串;坐标:数字; }'。 '{ postalCode: any; 类型中缺少属性 'city' }'。

我该如何处理这个问题?用户将推送邮政编码,而不是城市或坐标。我想我可以将任何类型的对象推送到数组中,但打字稿似乎阻止了这一点。

【问题讨论】:

    标签: javascript arrays angular typescript


    【解决方案1】:

    TypeScript 已将数组类型推断为 { city: string; postalCode: string; coordinates: number; }[] ,但您正在尝试推送 {postalCode:string} - 这是错误。如果您仍想这样做,则需要为location 设置适当的类型:

      location:any[]
      //or
      interface ILocation {
         city?:string;
         postalCode?:string;
         coordinates?:string;
      }
      location:ILocation[];
    

    【讨论】:

      【解决方案2】:

      您可以使用可选的citycoordinateslocations 声明为对象数组:

      type Loc = {city?: string; postalCode: string; coordinates?: number};
      
      let locations: Loc[] = [
        { city: 'Los Angelas', postalCode: '90001', coordinates: 2321 },
        { city: 'New York', postalCode: '10001', coordinates: 3432 },
      ];
      

      【讨论】:

        猜你喜欢
        • 2020-10-28
        • 2017-06-10
        • 2018-04-21
        • 2021-07-20
        • 2022-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多