简体   繁体   English

设置任何javascript对象属性的类型

[英]set type of any of javascript object property

I have the following javascript object 我有以下javascript对象

 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. 为了使图像查看器正常工作,我只需要图像的url,而不是图像url所包含的键。 So I take whats in the key and set the array position to the keys value, the image url. 因此,我将密钥中的内容作为变量并将数组位置设置为密钥值(图像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? 我怎么会

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 : 可以在设置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;

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

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