简体   繁体   English

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

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

I'm trying to use the bind method with curry , but it gives me a type error.我正在尝试将bind方法与curry一起使用,但它给了我一个类型错误。

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

Getting TS error from getSomething:从 getSomething 获取 TS 错误:

expected 0-1 arguments but got 2.预期 0-1 个参数,但得到 2 个。

When I am not using the bind method it's not complaining.当我不使用 bind 方法时,它不会抱怨。

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

The problem is that this is the signature of bind:问题是这是 bind 的签名:

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

So the return of bind for a function is any , curry still works because any can be converted to any other type, so the first overload in declaration order of curry is used namely this one:所以函数bind的返回值是anycurry仍然有效,因为any可以转换为任何其他类型,所以使用curry声明顺序中的第一个重载,即这个:

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

With T1 and R being inferred to {} . T1R被推断为{}

This is a reason to stay away from bind , it loses type info.这是远离bind一个原因,它会丢失类型信息。 It is difficult to write a general type safe version of bind , since it can bind both this and function arguments, but a version that just binds this and preserves type info in easy to write:很难编写一个通用类型安全的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);
}

Now using this version of bind all should work as expected (for functions with up to 5 arguments, but you can easily add more):现在使用这个版本的 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