1

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). 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; }' is not assignable to parameter of type '{ city: string; postalCode: string; coordinates: number; }'. Property 'city' is missing in type '{ postalCode: any; }'.

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.

2 Answers 2

3

TypeScript has inferred array type as { city: string; postalCode: string; coordinates: number; }[] , but you are trying to push {postalCode:string} - this is error. If you still want to do this then it is necessary to set appropriate type for location:

  location:any[]
  //or
  interface ILocation {
     city?:string;
     postalCode?:string;
     coordinates?:string;
  }
  location:ILocation[];
Sign up to request clarification or add additional context in comments.

Comments

1

You can declare locations as array of objects with optional city and coordinates:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.