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

TypeScript中如何让useRemote的execute严格校验参数类型与顺序

解决TypeScript中useRemote方法的参数类型校验问题

原代码的问题在于,useRemote的参数fn被定义为(...args: unknown[]) => void,这会让TypeScript丢失原函数的具体参数类型信息,导致Parameters<typeof fn>只能推断为unknown[],因此execute的参数不会做类型和顺序的严格校验。

修正后的代码

export function useRemote<T extends (...args: any[]) => void>(fn: T) {
  function execute(...args2: Parameters<T>) {
    fn(...args2);
  }
  return { execute };
}

原理说明

  • 通过泛型T捕获传入函数的完整类型(包括参数的类型、顺序和数量),而不是用宽泛的unknown[]来限制参数。
  • Parameters<T>是TypeScript内置工具类型,会准确提取出泛型T对应的函数参数类型元组,让execute的参数与原函数严格对齐。

使用验证

const { execute } = useRemote(
  (s: string, n: number) => somePromise(s, n)
);

execute("string", 0); // 编译成功
execute(0, "string"); // 编译失败,TypeScript会提示参数类型不匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 03:57:34