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

如何修改已有TypeScript类型的返回值类型?

解决方案

可以通过TypeScript的条件类型和infer关键字实现通用的ChangeReturnType工具类型,无需复制原函数类型的全部内容:

type ChangeReturnType<T extends (...args: any[]) => any, R> = 
  T extends (...args: infer Args) => any ? (...args: Args) => R : never;

验证基础用法

针对你给出的示例:

type Conditionalize = (...args: any[]) => string;
type ConditionalizeNum = ChangeReturnType<Conditionalize, number>;
// 等价于 type ConditionalizeNum = (...args: any[]) => number

修改React的FC类型

React原生FC类型的返回值仅限定为ReactElement | null,我们可以用上述工具类型扩展它,让返回值支持字符串、数字:

import type { FC, ReactElement } from 'react';

// 扩展FC的返回值类型
type ExtendedFC<P = {}> = ChangeReturnType<FC<P>, ReactElement | null | string | number>;

也可以直接自定义更贴合需求的组件类型:

import type { ReactElement, PropsWithChildren } from 'react';

type ExtendedFC<P = {}> = (props: PropsWithChildren<P>) => ReactElement | null | string | number;

之后就能用ExtendedFC定义返回字符串或数字的函数组件:

const TextComponent: ExtendedFC = () => "这是字符串返回值";
const NumberComponent: ExtendedFC = () => 2024;

内容的提问来源于stack exchange,提问作者Islam Y-

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:52:38