使用Next.js+TypeScript将动态类型化对象作为道具传递



我正在使用Next.js+TypeScript制作一个应用程序
在向组件传递道具时,我收到错误Type 'VoidFunctionComponent<ShirtDetailProps>' is missing the following properties。我该如何解决?

我应该提到的一件事是,对象的类型会根据其类别而变化
details应该是Details,但Details中的category_details可以是ShirtBag,具体取决于category_name

{
"data": {
"id": 1,
"details": [
{
"id": 1,
"category_name": "shirt",
"category_detail": {
"id": 1,
"size": "small",
"color": "white"
}
},
{
"id": 2,
"category_name": "bag",
"category_detail": {
"id": 13,
"width": 30,
"height": 15
}
},
{
"id": 3,
"category_name": "shirt",
"category_detail": {
"id": 45,
"size": "large",
"color": "pink"
}
}
]
}
}
export interface Box {
id: number;
details: Details[];
}
export interface Details {
id: number;
category_name: string;
category_detail: CategoryDetail[];
}
export interface Shirt {
id: number;
size: string;
color: string;
}
export interface Bag {
id: number;
width: number;
height: number;
}
export type CategoryDetail = Shirt | Bag;

话虽如此,我得到的错误如下:

const Foo: NextPage = () => {
const { box } = useFetchBox();
return (
<div>
{box.details.map((detail) => (
{detail.category_name === "shirt" && <ShirtDetail categroy_detail={detail.category_detail as unknown as typeof Shirt} />} // error: Type 'VoidFunctionComponent<ShirtDetailProps>' is missing the following properties from type 'ShirtDetail': id, size, color
{detail.category_name === "bag" && <BagDetail categroy_detail={detail.category_detail as unknown as typeof Bag} />} // error: Type 'VoidFunctionComponent<BagDetailProps>' is missing the following properties from type 'BagDetail': id, width, height
))}
</div>
)
}

ShirtDetail看起来很简单:

interface ShirtDetailProps {
category_detail: Shirt;
}
const ShirtDetail: React.VFC<ShirtDetailProps> = ({
category_detail,
}) => {
return (
// some code
);
};
export default ShirtDetail;

在我遇到这个错误之前,我尝试了以下步骤:

  1. categroy_detail={detail.category_detail as Shirt}给了我'Shirt' refers to a value, but is being used as a type here. Did you mean 'typeof Shirt'?
  2. 按照建议将其更改为category_detail={detail.category_detail as typeof Shirt},它给了我Conversion of type 'CategoryDetail[]' to type 'VFC<ShirtDetailProps>' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  3. 按照建议将其更改为category_detail={detail.category_detail as unknown as typeof Shirt},它给了我Type 'VoidFunctionComponent<ShirtDetailProps>' is missing the following properties from type 'Shirt': id, size, color
  4. 不知道怎么修

有人能帮我吗?

我的项目中定义了Shirt组件,这是我的错误。TypeScript与Shirt类型和Shirt组件混淆。我更改了Shirt组件的名称,错误随着categroy_detail={detail.category_detail as unknown as Shirt而消失。

最新更新