如何解决咖喱函数ts型标注的问题?

How to solve the problem of ts type labeling of curry functions?

提问人:lands 提问时间:7/4/2023 最后编辑:Martin H.lands 更新时间:7/5/2023 访问量:34

问:

/**
 * @type T Represents the type of the incoming function
 * @type First Represents the parameters entered for the first time
 */
type CurryFunc<T, First extends any[]> = T extends (
  ...args: infer Args
) => infer R
  ? // eslint-disable-next-line @typescript-eslint/no-unused-vars
    Args extends [...First, infer Mid, ...infer Tail]
    ? (v: Mid) => CurryFunc<T, [...First, Mid]>
    : R
  : T;

/**
 * Corialization function.  It can be deduced automatically according to the type of incoming function.
 * @param fn Functions that need to be Corey
 * @param rest The initial parameters of a function that needs to be Corialized
 * @returns Returns the return value of a new function that is Corialized or a function that needs to be Corialized
 * @example
 *  function add(a: number, b: number, c: number, d: number, e: number) {
 *    return a + b + c;
 *  }
 *  curry(add)(1)(2)(3)(4)(5);
 *  curry(add, 1)(2)(3)(4)(5);
 *  curry(add, 1, 2)(3)(4)(5);
 *  curry(add, 1, 2, 3)(4)(5);
 *  curry(add, 1, 2, 3, 4)(5);
 *  curry(add, 1, 2, 3, 4, 5);
 */

export function curry<T extends (...args: any[]) => any, First extends any[]>(
  fn: T,
  ...rest: First
): CurryFunc<T, First> {
  return function (...args: any[]): any {
    const currentArgs = [...rest, ...args];
    return currentArgs.length >= fn.length
      ? fn(...currentArgs)
      : curry(fn, ...currentArgs);
  } as CurryFunc<T, First>;
}

function add(a: number, b: number, c: number, d: number, e: number) {
  return a + b + c;
}
curry(add)(1)(2)(3)(4)(5);
curry(add, 1)(2)(3)(4)(5);
curry(add, 1, 2)(3)(4)(5);
curry(add, 1, 2, 3)(4)(5);
curry(add, 1, 2, 3, 4)(5);
curry(add, 1, 2, 3, 4, 5);
// @ts-ignore
curry(add, 1,2)(3,4)(5);

这是我对我的咖喱函数进行类型标记的实现,它无法解决 的错误问题。为了解决参数不定传输的问题,我需要做些什么?我想解决在第二次或多次调用中可以传递多个参数的问题,并带有自动类型提示。curry (add, 1,2) (3,4)(5);

JavaScript TypeScript 咖喱

评论

0赞 Dimava 7/5/2023
您可以尝试在 github.com/type-challenges/type-challenges 上找到答案

答: 暂无答案