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

如何在TypeScript中使用Parameters时对泛型函数强制执行类型安全?

解决泛型函数嵌套调用时的类型安全失效问题

问题分析

核心问题在于:当泛型函数funcExecutor作为参数传递给funcExecutorHandler时,TypeScript会对funcExecutor的泛型参数TFunc进行泛型擦除,导致Parameters<TAction>[0]无法关联到TFunc的具体类型。最终mapParams的返回类型被推断为any,完全失去了类型校验能力。

原来的funcExecutorHandler仅约束TAction为任意函数,但没有将TAction的泛型参数与自身泛型绑定,无法传递深层的类型约束关系。

解决方案

通过显式绑定funcExecutor的参数类型与funcExecutorHandler的泛型参数,保留TFunc的类型关联,即可恢复类型安全。

方案1:提取泛型接口复用

先把funcExecutor的入参类型抽为独立泛型接口,方便后续关联约束:

type ExecutorData<TFunc extends (...args: any[]) => void> = {
  func: TFunc;
  mapParams: () => Parameters<TFunc>[0];
};

重构funcExecutor使用该接口:

const funcExecutor = <TFunc extends (...args: any[]) => void>(data: ExecutorData<TFunc>) => {
  data.func(data.mapParams());
};

修改funcExecutorHandler,直接绑定TFunc泛型:

const funcExecutorHandler = <TFunc extends (...args: any[]) => void>(
  action: typeof funcExecutor,
  data: ExecutorData<TFunc>
) => {};

方案2:直接在Handler中定义约束

如果不想额外定义接口,可直接在funcExecutorHandler内显式写出约束:

const funcExecutorHandler = <TFunc extends (...args: any[]) => void>(
  action: typeof funcExecutor,
  data: {
    func: TFunc;
    mapParams: () => Parameters<TFunc>[0];
  }
) => {};

验证效果

此时调用funcExecutorHandler,TypeScript会正确关联func的参数类型与mapParams的返回类型:

funcExecutorHandler(funcExecutor, {
  func: (param: { foo: boolean }) => param,
  mapParams() {
    return {
      foo: 'bad', // 触发类型错误:"string"无法赋值给"boolean"
    };
  },
});

内容的提问来源于stack exchange,提问作者cyrus-d

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 19:47:31