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

React+TypeScript报错:Type 'undefined' is not assignable to type 问题求助

React+TypeScript报错:Type 'undefined' is not assignable to type 问题求助

兄弟,我瞅你这React+TypeScript的代码大概率是踩了useQuery返回值可能为undefined的坑,导致报了「Type 'undefined' is not assignable to type」的错。来给你分析分析原因和解决办法哈!

先把你贴的代码放这儿方便对照:

type TypeFetch = {
    success: boolean;
    paginate: Object;
    data: {
        uuid: string;
        title: string;
        created_at: string;
        updated_at?: string | undefined;
        deleted_at?: string | undefined;
    }[];
};

const Index = () => {
    ...

    const { data: fetchData, status: fetchStatus } = useQuery<TypeFetch>({
        queryKey: [/* 你这里的thisInfo相关内容 */],
        // 你的请求逻辑
    });

    // 这里直接用fetchData的话就容易触发报错
};

核心问题其实很简单:useQuery在请求还没完成(pending状态)或者请求失败(error状态)时,返回的data是undefined,但你给useQuery指定的类型是TypeFetch——也就是必须存在的确定类型,TypeScript的类型检查自然就跳出来报错了。

给你几个实用的解决办法,你可以按需选:

  • 先判断状态再使用数据
    最稳妥的方式就是先等请求成功,确认数据存在后再用,TypeScript会自动推导类型:
if (fetchStatus === 'success' && fetchData) {
  // 这里放心用fetchData就行,TS已经知道它是TypeFetch类型了
  console.log(fetchData.data.map(item => item.title));
}
  • 给类型加上undefined联合类型
    如果你能接受data可能为undefined,可以直接把useQuery的类型改成TypeFetch | undefined,这样类型就匹配了:
const { data: fetchData, status: fetchStatus } = useQuery<TypeFetch | undefined>({
    queryKey: [/* 你的queryKey内容 */],
    queryFn: () => {
        // 你的请求逻辑,比如fetch然后返回数据
    }
});
  • 用可选链操作符兜底
    在访问fetchData的属性时加上可选链?.,既可以避免运行时的报错,也能让TypeScript闭嘴:
// 比如访问data数组,用空数组兜底
const items = fetchData?.data ?? [];
// 访问paginate的属性
const currentPage = fetchData?.paginate?.currentPage;

另外提个小建议:你的TypeFetch里paginate用了Object类型,这其实太宽泛了,建议定义成具体的接口,类型检查会更严谨,比如:

// 先定义paginate的具体类型
type PaginateConfig = {
    page: number;
    pageSize: number;
    totalItems: number;
};

type TypeFetch = {
    success: boolean;
    paginate: PaginateConfig; // 换成具体类型
    data: {
        uuid: string;
        title: string;
        created_at: string;
        updated_at?: string;
        deleted_at?: string;
    }[];
};

你先试试这些办法,要是还有问题,把报错的具体位置和更多相关代码贴出来,我再帮你排查!

备注:内容来源于stack exchange,提问作者Mr.Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 16:49:43