user9487981
user9487981

Reputation:

set type of any of javascript object property

I have the following javascript object

 venue = {
    id: 0,
    name: '',
    venueimage_set: [
      {
        imageurl: '',
      },

    ]...

then later in my code I change the object:

 this.venue.venueimage_set[+image] = this.venue.venueimage_set[+image].imageurl;

for a image viewer to work I need the url of the image only not the key that the image url is part of. So I take whats in the key and set the array position to the keys value, the image url.

then I get this noise.

ERROR in mainroot/venuepage/venuepage.component.ts(171,25): error TS2322: Type 'string' is not assignable to type '{ imageurl: string; }'. mainroot/venuepage/venuepage.component.ts(175,127): error TS2339: Property 'imageurl' does not exist on type 'string'.

I would like typescript to ignore typing and just let me do this. How would I?

Upvotes: 0

Views: 181

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138297

Here is a typesafe version of what you're trying to do:

function toVenue<T>({id, name, venueimage_set}: T) {
  return {
    id,
    name,
    venueImageSet: venueimage_set.map(el => el.imageurl)
  };
}

Which can be used when setting venue:

const venue = toVenue({
    id: 0,
    name: '',
    venueimage_set: [{
       imageurl: '',
    }]
});

And here the unsafe version (please don't do this):

this.venue.venueimage_set[+image] = this.venue.venueimage_set[+image].imageurl as any;

Upvotes: 2

Related Questions