繁体   English   中英

Lodash 使用带有绑定的 curry 导致打字稿错误

[英]Lodash using curry with bind cause a typescript error

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

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

从 getSomething 获取 TS 错误:

预期 0-1 个参数,但得到 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版本,因为它可以绑定this和函数参数,但是一个只绑定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.
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM