在TypeScript中以完美的方式定义对象数组?

问题描述 投票:0回答:3

我正在使用TS 3.7.4,并且相信现在大多数类型都是通过接口制成的。

我有一个看起来像这样的道具:

  images={
    [
      {
        image: 'https://www.commerciallistings.cbre.co.uk//resources/fileassets/GB-Plus-480572/09e35192/11%20Strand%201_Photo_1_small.jpg',
        altTag: "An Image"
      },
      {
        image: 'https://www.commerciallistings.cbre.co.uk//resources/fileassets/GB-Plus-480572/09e35192/11%20Strand%201_Photo_1_small.jpg',
        altTag: "An Image"
      }
    ]
  }

我想使用界面,因为我觉得这不太冗长。

我尝试过:

 images: Array[object]
javascript typescript
3个回答
0
投票

首先为图像对象创建一个接口。然后将图像prop声明为该接口的array和数组。

Interface Image {
  image?: String;
  altTag?: String;
}

...

images: Image[]  

0
投票

老实说,我不建议您屈服,但我建议您阅读文档,因为这是一项非常基本的任务,如果您无法正确掌握这些基础知识,将来您会很费劲。


  1. 首先,您需要定义您的Image对象Interface。简单地传递一个默认的Object作为类型,几乎破坏了的用途-您想要尽可能地明确,这几乎不是一个好主意。

    interface ImageType {
       image: string,
       altTag: string,
    }
    
  2. 然后定义您的道具

    interface Props {
      images: ImageType[] // Alternatively Array<ImageType>
    }
    
    const MyComponent: React.FC<Props> = (props: Props) => {
      // ...
    }
    

0
投票

您可以创建如下界面:

export interface ImageProps{
  image: string,
  altTag: string
}

您可以像这样使用它:

const Image = ({ props: ImageProps[] }){
  // Your code here.
}

希望这对您有用。

© www.soinside.com 2019 - 2024. All rights reserved.