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

如何在TypeScript中简化与复用函数参数?

TypeScript 简化GraphQL函数参数复用方案

你可以通过元组切片或Omit结合Parameters两种方式复用RequestGraphqlServer的参数类型,避免重复定义UseQuery和UseMutation的参数:

方案一:元组切片(TypeScript 4.0+ 推荐)

TypeScript 4.0及以上支持元组类型的切片操作,直接截取RequestGraphqlServer参数列表中从第2个开始的部分:

export type RequestGraphqlServer = (
  queryType: "query" | "mutation",
  operationName: string,
  requestData: string,
  variables?: object | null,
  options?: IGraphqlQueryOptions
) => IResponseType;

// 截取 RequestGraphqlServer 除第一个参数外的所有参数
type GraphqlSharedParams = Parameters<RequestGraphqlServer>[1:];

// 复用参数类型定义 UseQuery 和 UseMutation
export type UseQuery = (...args: GraphqlSharedParams) => ReturnType<RequestGraphqlServer>;
export type UseMutation = (...args: GraphqlSharedParams) => ReturnType<RequestGraphqlServer>;

方案二:Omit结合Parameters(兼容旧版TypeScript)

如果项目使用低于4.0的TypeScript版本,可以用Omit移除元组的第一个索引(索引为0的元素):

export type RequestGraphqlServer = (
  queryType: "query" | "mutation",
  operationName: string,
  requestData: string,
  variables?: object | null,
  options?: IGraphqlQueryOptions
) => IResponseType;

// 移除参数列表中索引为0的元素
type GraphqlSharedParams = Omit<Parameters<RequestGraphqlServer>, 0>;

export type UseQuery = (...args: GraphqlSharedParams) => ReturnType<RequestGraphqlServer>;
export type UseMutation = (...args: GraphqlSharedParams) => ReturnType<RequestGraphqlServer>;

两种方案都能实现参数复用,确保UseQuery、UseMutation与RequestGraphqlServer的参数(除第一个queryType外)保持一致,后续修改RequestGraphqlServer的参数时,另外两个类型会自动同步更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 09:37:10