简体   繁体   English

使用interfect在TypeScript中定义对象数组?

[英]Defining an array of objects in TypeScript with interfect?

I am using TS 3.7.4 and believe most types are now made with interfaces.我正在使用TS 3.7.4 并且相信大多数类型现在都是用接口制作的。

I have a prop that looks like this:我有一个看起来像这样的道具:

  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"
      }
    ]
  }

I would like to use interface as I find this less verbose.我想使用界面,因为我觉得这不那么冗长。

I have tried:我试过了:

 images: Array[object]

You can create a interface like:您可以创建一个界面,如:

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

And you can use it like:你可以像这样使用它:

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

Hope this works for you.希望这对你有用。

First create an interface for the image object.首先为图像对象创建一个接口。 Then declare the images prop to be and array of that interface.然后将图像属性声明为该接口的数组。

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

...

images: Image[]  

Honestly, without meaning to sound condescending, I'd recommend reading up on the docs as this is fairly basic task and you'll struggle in the future if you won't get the basics down right.老实说,我不想显得居高临下,我建议您阅读文档,因为这是一项相当基本的任务,如果您没有掌握正确的基础知识,您将来会很挣扎。


  1. First you need to define your Image object Interface.首先你需要定义你的 Image 对象接口。 It's almost never a good idea to simply pass a default Object as a type and kind of defeats the purpose of - as you want to be as explicit as possible.简单地将默认Object作为类型传递几乎从来都不是一个好主意,并且有点违背的目的 - 因为您希望尽可能明确。

     interface ImageType { image: string, altTag: string, }
  2. Then define your props然后定义你的道具

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

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

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