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

Type 'undefined'无法赋值给'Products'的TypeScript类型错误排查

解决TypeScript解构时的类型错误问题

问题背景

产品数据获取后展示功能正常,但解构语句处触发TypeScript类型错误,相关代码及错误信息如下:

fetch函数代码

export async function fetchAllProducts() {
  try {
    const res = await axios.get(url);
    const data = res.data;
    return {
      data
    }
  } catch(err) {
    if(err instanceof AxiosError)
      return {
        error: err.message
      }
  }
}

组件使用代码

export default async function StorePage() {
 const { data, error }: Products = await fetchAllProducts(); // 此处data和error标红报错
  
  return (
    <section className='section'>
      <div className='section__inner'>
        <h4 className='section__title'>Products</h4>
        {error && <span>{error}</span>}
        {!data && !error && <span>loading...</span>}
        <div className='section__content products-container'>
          {!error && data && data?.length > 0 && data.map((product: ProductProps) => <ProductCard key={product.id} {...product}/>)}
        </div>
      </div>
    </section>
  )
}

错误信息

Type '{ data: any; error?: undefined; } | { error: string; data?: undefined; } | undefined' is not assignable to type 'Products'. Type 'undefined' is not assignable to type 'Products'.

类型定义

export type Products = {
  data: ProductProps[] | null;
  error: string | undefined;
}

export type ProductProps = {
  id: string;
  title: string;
  category: string;
  description: string;
  image: string;
  price: number;
  rating: {
    rate: number,
    count: number
  }
}

错误原因

  1. fetch函数未指定返回类型:TypeScript自动推断的返回类型为{data: any} | {error: string} | undefined,与定义的Products类型结构不匹配。Products要求同时包含data和error字段,但fetch返回的是要么只有data、要么只有error的对象,甚至可能返回undefined(当catch捕获的错误不是AxiosError时)。
  2. axios请求未指定响应类型:res.data被推断为any,丢失了TypeScript的类型校验能力。

解决方案

步骤1:给fetch函数添加返回类型并统一返回结构

修改fetchAllProducts,确保返回结构严格匹配Products类型,同时为axios请求指定响应数据类型:

import axios, { AxiosError } from 'axios';
import { Products, ProductProps } from './types'; // 替换为你的类型文件路径

export async function fetchAllProducts(): Promise<Products> {
  try {
    // 给axios.get指定泛型,让res.data自动推导为ProductProps[]类型
    const res = await axios.get<ProductProps[]>(url);
    return {
      data: res.data,
      error: undefined
    };
  } catch (err) {
    if (err instanceof AxiosError) {
      return {
        data: null,
        error: err.message
      };
    }
    // 处理非AxiosError类型的错误,避免返回undefined
    return {
      data: null,
      error: '未知错误'
    };
  }
}

步骤2:简化组件中的类型声明

由于fetch函数已明确返回Promise<Products>,组件中无需手动指定类型:

export default async function StorePage() {
 const { data, error } = await fetchAllProducts(); // 移除: Products
  
  // 组件其余代码保持不变
}

总结

问题核心确实和fetch函数未添加类型定义有关,同时fetch的返回结构与Products类型不匹配,且存在返回undefined的情况,导致TypeScript类型校验失败。通过统一返回结构并明确类型定义,即可解决该错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 10:42:45