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

React/TypeScript中如何优雅处理组件Props的函数参数类型?

问题描述

我有如下代码:

type Props = {
  onClose: () => void
} 
const MyComponent = ({ onClose }: Props) => {
 // my component
}

但实际上onClose可以是任意带参数的函数,参数类型可能是string、number等。我试过用泛型,但如果有多个这类函数,就要定义多个泛型,显得很繁琐:

type Props<T> = {
  onClose: (arg: T) => void
} 
const MyComponent<T> = ({ onClose }: Props<T>) => {
 // my component
}

有没有更简洁优雅的处理方式?(不想使用any类型)

解决方案

1. 使用unknown定义参数类型

用unknown替代any,既保留类型安全,又兼容任意参数类型,调用时可通过类型收窄处理参数:

type Props = {
  onClose: (arg: unknown) => void
} 
const MyComponent = ({ onClose }: Props) => {
  // 调用示例:
  // onClose('test');
  // onClose(123);
}

2. 支持任意参数的函数类型

如果不需要约束参数数量和类型,可定义接受任意参数的函数类型:

type Props = {
  onClose: (...args: unknown[]) => void
} 
const MyComponent = ({ onClose }: Props) => {
  // 支持任意数量、类型的参数传入
}

3. 单个泛型约束多回调参数

如果有多个同类型回调,用泛型元组统一约束参数,避免多个泛型:

type Props<T extends unknown[]> = {
  onClose: (...args: T) => void
  onConfirm: (...args: T) => void
} 
const MyComponent = <T extends unknown[]>({ onClose, onConfirm }: Props<T>) => {
  // 所有回调共享同一组参数类型
}

4. 自动推导函数类型

让TypeScript根据传入的回调自动推导类型,无需提前定义泛型:

const MyComponent = <T extends (...args: unknown[]) => void>({ onClose }: { onClose: T }) => {
  // 自动适配传入的onClose参数类型
}

// 使用示例:
MyComponent({ onClose: (arg: string) => {} });
MyComponent({ onClose: (arg: number) => {} });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:15:56