javascript - Lodash 将 curry 与 bind 结合使用会导致 typescript 错误

标签 javascript typescript lodash

我正在尝试将 bind 方法与 curry 一起使用,但它给了我一个类型错误。

const curried = curry(this.method.bind(this));
const getSomething = curried(a, b);

从 getSomething 获取 TS 错误:

expected 0-1 arguments but got 2.

当我不使用绑定(bind)方法时,它不会提示。

const curried = curry(this.method);
const getSomething = curried(a, b);

最佳答案

问题是这是绑定(bind)的签名:

bind(this: Function, thisArg: any, ...argArray: any[]): any;

所以bind对于函数的返回是anycurry仍然有效,因为any可以转换到任何其他类型,所以使用 curry 声明顺序中的第一个重载,即这个:

curry<T1, R>(func: (t1: T1) => R, arity?: number): CurriedFunction1<T1, R>;

T1R 被推断为 {}

这是远离 bind 的原因,它会丢失类型信息。很难编写 bind 的通用类型安全版本,因为它可以绑定(bind) this 和函数参数,但是只绑定(bind) this 的版本> 并以易于编写的方式保留类型信息:

function typedThisBind<T1, T2, T3, T4, R>(fn: (t: T1, t2: T2, t3: T3, t4 : T4) => R, thisArg: any) : typeof fn
function typedThisBind<T1, T2, T3, R>(fn: (t: T1, t2: T2, t3: T3) => R, thisArg: any) : typeof fn
function typedThisBind<T1, T2, R>(fn: (t: T1, t2: T2) => R, thisArg: any) : typeof fn
function typedThisBind<T1, R>(fn: (t: T1) => R, thisArg: any) : typeof fn
function typedThisBind<R>(fn: () => R, thisArg: any) : () => R
function typedThisBind(fn: Function, thisArg: any) : any {
    return fn.bind(thisArg);
}

现在使用这个版本的 bind all 应该可以按预期工作(对于最多有 5 个参数的函数,但您可以轻松添加更多):

class Foo {
    method(a: number, b: number) {}
    m(){
        const curried = curry(typedThisBind(this.method, this));
        const getSomething = curried(0, 0); // Works as expected.
    }
}

关于javascript - Lodash 将 curry 与 bind 结合使用会导致 typescript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48627043/

相关文章:

javascript - 比较对象的两个深层嵌套对象并仅返回 javascript/lodash 中的差异

javascript - 无法同时使用 2 个 javascript 表单函数

javascript - Angular : How to get value in html passing to other component?

angular - Ionic 2 - 如何仅删除登录页面上的拆分面板?

javascript - 使用 lodash 从数组返回对象属性

javascript - 在 Javascript 中缓存去抖函数

javascript - 绑定(bind)图像未在 Vue 项目中显示

javascript - 正则表达式匹配第一个字符之前和最后一个字符之后的空格或符号之间的字符串

javascript - 环回Mysql连接器: BIT(1) is recognized always true

Typescript - isEmpty 函数的通用类型保护