next.js 类型错误:“属性在类型上不存在”,而实际上它确实存在

e4yzc0pl  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(156)

我在构建过程(Vercel)中遇到了一个错误,product被传递到CartItem.tsx中,尽管它是在types.tsx中声明的。
错误:

  1. Type error: Property 'imageUrl' does not exist on type 'Product'.
  2. 43 | <div className="flex items-center">
  3. 44 | <Image
  4. > 45 | src={product.imageUrl}
  5. | ^
  6. 46 | alt={product.itemName}
  7. 47 | width={100}
  8. 48 | height={100}

字符串

CartItem.tsx:

  1. import { Product } from "types/types";
  2. import Image from "next/image";
  3. export default function CartItem({ product }: { product: Product }) {
  4. /* ... */
  5. return (
  6. <div className="flex items-center">
  7. <Image
  8. src={product.imageUrl}
  9. alt={product.itemName}
  10. width={100}
  11. height={100}
  12. className="h-10 w-10 rounded-full mr-4 object-cover"
  13. />
  14. {* ... *}
  15. </div>
  16. );
  17. }

types.tsx:

  1. /* ... */
  2. export type Product = {
  3. id: number;
  4. restaurantId: number;
  5. itemName: string;
  6. restaurantName: string;
  7. imageUrl: string;
  8. // title: string;
  9. description: string;
  10. price: number;
  11. // discountPercentage: number;
  12. // rating: number;
  13. // stock: number;
  14. // brand: string;
  15. // category: string;
  16. // thumbnail: string;
  17. // images: string[];
  18. quantity?: number;
  19. };

wlp8pajw

wlp8pajw1#

根据你写的代码,它应该可以工作。我会尝试暂时将您的类型定义移动到与CartItem相同的文件中,看看是否解决了问题-如果解决了,那么您的类型导入方式一定有问题。
还有一个侧记:你可以使用React.FC类型来更干净地类型化组件。

  1. type CartItemTwoProps = { product: Product };
  2. const CartItemTwo: React.FC<CartItemTwoProps> = ({ product }) => {
  3. return (
  4. product.imageUrl // works
  5. );
  6. }

字符串
TSPlayground

相关问题