打字稿“非”函数

时间:2021-02-22 17:13:05

标签: typescript generics types functional-programming typescript-generics

如何告诉 TypeScript 将上面 fn 的参数类型连接到下面 ...args 的参数类型??

  /**
   * @template F
   * @param {(...o: Parameters<F>) => boolean} fn
   */
  function not(fn) {
    return (
      /**
       * @param {Parameters<F>} args
       * @returns {boolean}
       */
      (...args) => {
        return !fn(...args);
      }
    );
  }

1 个答案:

答案 0 :(得分:4)

既然你在使用 JSDoc,我想我会这样写:

/**
 * @template {any[]} A
 * @param {(...args: A)=>boolean} fn
 */
function not(fn) {
  return (
    /**
     * @param {A} args
     * @returns {boolean}
     */
    (...args) => {
      return !fn(...args);
    });
}

重点是在 A 中是泛型的,args 的类型而不是 F 中的可能是函数类型。

你可以测试一下:

/**
 * @param {string} x
 * @param {number} y
 */
function hmm(x, y) {
  return x.length === y;
}

const notHmm = not(hmm);
notHmm("", 2)
notHmm(123, "") // error!
// --> ~~~
// Argument of type 'number' is not assignable to parameter of type 'string'.(2345)
notHmm(); // error!
// Expected 2 arguments, but got 0.(2554)

看起来不错。

Playground link to code

在 TS 中

function not<A extends any[]>(
  fn: (...args: A) => boolean
) {
  return (
    (...args: A) => {
      return !fn(...args);
    });
}

Playground link to code