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

React TypeScript:根据Endpoint参数返回对应类型的类型报错求助

问题分析与解决方案

问题出在DataComp的Props定义上:children的参数类型被设为Response<Data> | Response<DataWidthLabel>的联合类型,TypeScript无法根据传入的endpoint值自动推断出当前children参数的具体类型,所以在ParentComp2中访问data.data.labels时,TypeScript无法确定data.data是否包含labels字段,从而抛出类型错误。

修改步骤

  1. 将Props改为泛型类型,关联具体的Endpoint类型
  2. 把DataComp声明为泛型组件,接收泛型参数T extends Endpoint
  3. 让children的参数类型与当前endpoint对应的响应类型FnResponse<T>绑定,实现类型联动

修改后的完整代码

import React from "react";

type Response<T> = {
  data: T;
  description: string;
  date: string;
};
type Data = {
  title: string;
  name: string;
};
type DataWithLabel = Data & { labels: string };
type Endpoint = "endpoint_1" | "endpoint_2";

type FnResponse<T> = 
  T extends "endpoint_1" ? Response<Data> :
  T extends "endpoint_2" ? Response<DataWithLabel> : never;

// 泛型Props,关联Endpoint类型T
type Props<T extends Endpoint> = {
  endpoint: T;
  children: (data: FnResponse<T>) => React.ReactNode;
};

function queryFunction<T extends Endpoint>(endpoint: T): FnResponse<T> {
  if (endpoint === "endpoint_1") {
    return {
      data: {
        title: "title",
        name: "name"
      },
      description: "description",
      date: "date"
    } as FnResponse<T>;
  }

  return {
    data: {
      title: "title",
      name: "name",
      labels: "labels"
    },
    description: "description",
    date: "date"
  } as FnResponse<T>;
}

// 泛型React组件
const DataComp = <T extends Endpoint>({ endpoint, children }: Props<T>) => {
  const data = queryFunction(endpoint);

  return (
    <div>
      {children(data)}

      <div>
        <p>{data.description}</p>
        <p>{data.date}</p>
      </div>
    </div>
  );
};

const ParentComp1 = () => (
  <DataComp endpoint="endpoint_1">
    {(data) => {
      return data.data.name;
    }}
  </DataComp>
);

const ParentComp2 = () => (
  <DataComp endpoint="endpoint_2">
    {(data) => {
      return data.data.labels;
    }}
  </DataComp>
);

export default function App() {
  return (
    <div className="App">
      <ParentComp1 />
      -----
      <ParentComp2 />
    </div>
  );
}

关键改动说明

  • 修正拼写错误:DataWidthLabel改为DataWithLabel,更符合语义
  • Props变为泛型,让endpoint的类型和children参数类型强关联
  • DataComp作为泛型组件,TypeScript会根据传入的endpoint自动推断children参数的具体类型
  • 调整children的返回类型为React.ReactNode,符合React组件返回值要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 15:55:14