You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中GraphQL TypeScript类型使用问题:Keystone.js后端下Product组件Props类型定义错误解决

Correcting Props Type for Your Product Component

Let's break down what's going wrong here and fix it step by step.

The Root of the Error

Your current Product component is trying to use ProductData_allProducts directly as its props type. But in reality, you're passing a props object with a product property to the component, not the product data itself. TypeScript is complaining because ProductData_allProducts doesn't have a product property—it is the product data.

Fix 1: Define a Proper Props Interface

First, create a dedicated interface for your Product component's props that explicitly declares the product property and its type:

import React from 'react';
import { ProductData_allProducts } from '../generated/ProductData';

// Define the props shape your component expects
interface ProductProps {
  product: ProductData_allProducts;
}

const Product = ({ product }: ProductProps) => {
  // Since product might have nullable properties, add safeguards for optional fields
  return <p>{product.name ?? 'Unnamed Product'}</p>;
};

export default Product;

Fix 2: Handle Nullable Products from the Query

Your generated ProductData type shows allProducts is (ProductData_allProducts | null)[] | null—meaning individual items could be null. To avoid passing null to your Product component, filter out null values before mapping:

// In your Products component
{data?.allProducts
  ?.filter((product): product is ProductData_allProducts => product !== null)
  .map(product => (
    <Product product={product} key={product.id} />
  ))}

Alternatively, if you want your Product component to handle null inputs directly, update the props interface to allow it and add a guard clause:

interface ProductProps {
  product: ProductData_allProducts | null;
}

const Product = ({ product }: ProductProps) => {
  if (!product) return null; // Or render a placeholder like "Product not found"
  return <p>{product.name ?? 'Unnamed Product'}</p>;
};

Why This Works

By defining a ProductProps interface, you're telling TypeScript exactly what shape of props your component accepts: an object with a product key that holds a ProductData_allProducts (or nullable) value. This perfectly matches how you're passing data from the parent Products component, eliminating the type mismatch errors.

内容的提问来源于stack exchange,提问作者lomine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 06:54:13