Home > Enterprise >  Writing interface for array of objects and with array included with same objects
Writing interface for array of objects and with array included with same objects

Time:01-14

Here is my array, i like to iterate: it has single object an array of object. how to write interface for it? how to replace any[] with appropriate declaration?

code :`

export const initialPhotoProps:any[] = 

[
  {
    urls: {
      sm: "/assets/mobile/model_front.jpg",
      lg: "/assets/desktop/model_front.jpg",
    },
    id: "model-front",
    alt: "Model front photo",
    caption: "mcdayen",
  },
  [
    {
      urls: { sm: null, lg: "/assets/desktop/model_back.jpg" },
      id: "model-back",
      alt: "Model back photo",
      caption: "mcdayen",
    },
    {
      urls: { sm: null, lg: "/assets/desktop/model_back.jpg" },
      id: "model-back",
      alt: "Model back photo",
      caption: "mcdayen",
    },
  ],
  {
    urls: { sm: null, lg: "/assets/desktop/model_back.jpg" },
    id: "model-back",
    alt: "Model back photo",
    caption: "mcdayen",
  },
];

`

export interface PhotoProps {
urls: { sm: string|null; lg:string|null}
id: string;
alt: string;
caption: string;
}

export const initialPhotoProps: PhotoProps[] - but throws error from array section. how to mix and write the interface?

Need the interface to mix both object and array

CodePudding user response:

Since your array allows both PhotoProps and an array of PhotoProps as valid elements, you have use a union of PhotoProps | PhotoProps[] to type the array resulting in (PhotoProps | PhotoProps[])[].

export const initialPhotoProps: (PhotoProps | PhotoProps[])[] = [
  /* ... */
]

export type PhotoPropsArray = (PhotoProps | PhotoProps[])[]

Playground

  • Related