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

TanStack Query TypeError:TodoType[]不存在todos属性问题求助

解决TanStack Query中Todo列表的类型错误

问题核心是getTodos函数的返回类型声明错误:DummyJson的/todos接口返回的是包含todos数组的对象(匹配你定义的TodosType),但你错误将返回类型设为TodoType[],导致TypeScript认为查询结果是数组而非带todos属性的对象,从而抛出类型错误。

修复步骤:

  • 修正api/getTodos.ts的返回类型
    将getTodos的返回类型从TodoType[]改为TodosType,确保和API返回结构、你的类型定义匹配:

    // api/getTodos.ts
    import { TodosType } from '../types';
    
    export const getTodos = async (): Promise<TodosType> => {
      const res = await fetch('https://dummyjson.com/todos');
      if (!res.ok) throw new Error('Failed to fetch todos');
      return res.json();
    };
    
  • 在TodoWrapper组件中正确访问数据
    现在todosQuery.data的类型为TodosType,可以安全访问.todos属性:

    // TodoWrapper.tsx
    import { useQuery } from '@tanstack/react-query';
    import { getTodos } from './api/getTodos';
    import { TodosType } from './types';
    
    export const TodoWrapper = () => {
      const todosQuery = useQuery({
        queryKey: ['todos'],
        queryFn: getTodos,
      });
    
      if (todosQuery.isLoading) return <div>Loading...</div>;
      if (todosQuery.isError) return <div>Error: {todosQuery.error?.message}</div>;
    
      return (
        <div>
          {todosQuery.data?.todos.map(todo => (
            <div key={todo.id}>{todo.todo}</div>
          ))}
        </div>
      );
    };
    
  • 确认类型定义正确性
    保证types/index.ts中的结构和API返回一致:

    // types/index.ts
    export interface TodoType {
      id: number;
      todo: string;
      completed: boolean;
      userId: number;
    }
    
    export interface TodosType {
      todos: TodoType[];
      total: number;
      skip: number;
      limit: number;
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:22:07