typescript 对象数组的写入接口,且数组包含在相同对象中

bnl4lu3b  于 2023-01-14  发布在  TypeScript
关注(0)|答案(1)|浏览(88)

这是我的数组,我喜欢迭代:它有一个对象数组。2如何为它写接口?3如何用适当声明替换any[]
代码:'

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;
}

但是从数组部分抛出错误。如何混合和编写接口?
需要混合对象和数组的接口

i2byvkas

i2byvkas1#

由于您的数组允许PhotoPropsPhotoProps数组作为有效元素,因此您必须使用PhotoProps | PhotoProps[]的并集来键入生成(PhotoProps | PhotoProps[])[]的数组。

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

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

Playground

相关问题