简体   繁体   English

将对象推入数组的函数中的打字稿错误

[英]Typescript Errors in Function Pushing Objects to an Array

I am trying to push new objects to an array in my Angular 2 app, but I am running into an issue (which I suspect may be a Typescript type issue, though I'm not certain). 我正在尝试将新对象推送到Angular 2应用程序中的数组,但遇到了一个问题(尽管不确定,我怀疑这可能是Typescript类型问题)。 This is what the array I'm pushing to looks like: 这就是我要推入的数组:

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

And here is the function I am using to push new zipcodes to the array with: 这是我用来通过以下方式将新邮政编码推入阵列的函数:

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

The error I'm getting re: this function is: 我得到的错误是:该函数是:

Argument of type '{ postalCode: any; 类型'{postalCode:any; }' is not assignable to parameter of type '{ city: string; }'不可分配给类型'{city:string; postalCode: string; postalCode:字符串; coordinates: number; 坐标:数字; }'. }'。 Property 'city' is missing in type '{ postalCode: any; 类型'{postalCode:any;中缺少属性'city'。 }'. }'。

How can I deal with this issue? 我该如何处理? Users will be pushing postalCodes, not cities or coordinates. 用户将推送邮政编码,而不是城市或坐标。 I would think I could push an object of any kind to the array, but it seems typescript is preventing this. 我想我可以将任何类型的对象推入数组,但是看来打字稿正在阻止这种情况。

TypeScript has inferred array type as { city: string; postalCode: string; coordinates: number; }[] TypeScript已将数组类型推断为{ city: string; postalCode: string; coordinates: number; }[] { city: string; postalCode: string; coordinates: number; }[] { city: string; postalCode: string; coordinates: number; }[] , but you are trying to push {postalCode:string} - this is error. { city: string; postalCode: string; coordinates: number; }[] ,但您正在尝试推送{postalCode:string} -这是错误的。 If you still want to do this then it is necessary to set appropriate type for location : 如果您仍然想这样做,则必须为location设置适当的类型:

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

You can declare locations as array of objects with optional city and coordinates : 您可以将locations声明为具有可选citycoordinates的对象数组:

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

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

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