我正在尝试将 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
对于函数的返回是any
,curry
仍然有效,因为any
可以转换到任何其他类型,所以使用 curry
声明顺序中的第一个重载,即这个:
curry<T1, R>(func: (t1: T1) => R, arity?: number): CurriedFunction1<T1, R>;
T1
和 R
被推断为 {}
。
这是远离 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/