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

React/Next.js中API响应类型的导出导入及复用方案咨询

在React/Next.js中复用API类型的正确做法

一、快速解决当前报错

1. 导出类型

在pages/users.tsx中,给Post类型加上export关键字,让它能被其他文件引用:

// pages/users.tsx
export type Post = {
  id: number;
  name: string;
  username: string;
  email: string;
  address: {
    street: string;
    suite: string;
    city: string;
    zipcode: string;
    geo: {
      lat: string;
      lng: string;
    };
  };
  phone: string;
  website: string;
  company: {
    name: string;
    catchPhrase: string;
    bs: string;
  };
};

2. 导入类型

在pages/user.tsx中导入这个Post类型:

// pages/user.tsx
import { FC } from "react";
// 从users.tsx导入Post类型
import type { Post } from "./users";

type Props = {
  posts: Post[];
};

// 其余组件代码不变

二、规范的类型管理方案

如果这个Post类型需要在多个页面/组件中复用,创建全局类型文件夹统一管理是更优的选择,比分散在各目录的types.ts更易维护:

1. 创建全局类型文件

在项目根目录新建types文件夹,里面创建api.ts(或user.ts)专门存放API相关类型:

// types/api.ts
export type Post = {
  id: number;
  name: string;
  username: string;
  email: string;
  address: {
    street: string;
    suite: string;
    city: string;
    zipcode: string;
    geo: {
      lat: string;
      lng: string;
    };
  };
  phone: string;
  website: string;
  company: {
    name: string;
    catchPhrase: string;
    bs: string;
  };
};

2. 在需要的文件中导入

修改pages/users.tsx:

// pages/users.tsx
// 从全局类型文件导入Post
import type { Post } from "../types/api";

// 其余代码(getStaticProps和组件部分不变)

修改pages/user.tsx:

// pages/user.tsx
import { FC } from "react";
// 从全局类型文件导入Post
import type { Post } from "../types/api";

type Props = {
  posts: Post[];
};

// 其余组件代码不变

三、方案选择建议

  • 如果类型仅在少量关联文件中复用,临时导出导入可以应付,但长期维护来看,统一管理更靠谱。
  • 全局类型文件夹的优势:
    • 所有API响应类型集中存放,修改时不用到处找文件
    • 避免重复定义相同类型,减少代码冗余
    • 团队协作时,成员能快速定位所有公共类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:25:07