与bind函数套用,并在TypeScript中正确键入泛型



我已经编写了一个排序函数,并希望将比较函数绑定到它。不幸的是,TypeScript编译器警告我比较函数的unknown类型。

我已经尝试搜索SO:绑定函数到函数并在TS手册中搜索:bind。但是,我找不到任何相关的问题。

并尝试遵循声明文件中的类型:

/**
* For a given function, creates a bound function that has the same body as the original function.
* The this object of the bound function is associated with the specified object, and has the specified initial parameters.
* @param thisArg The object to be used as the this object.
* @param args Arguments to bind to the parameters of the function.
*/
bind<T>(this: T, thisArg: ThisParameterType<T>): OmitThisParameter<T>;
bind<T, A0, A extends any[], R>(this: (this: T, arg0: A0, ...args: A) => R, thisArg: T, arg0: A0): (...args: A) => R;
bind<T, A0, A1, A extends any[], R>(this: (this: T, arg0: A0, arg1: A1, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1): (...args: A) => R;
bind<T, A0, A1, A2, A extends any[], R>(this: (this: T, arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2): (...args: A) => R;
bind<T, A0, A1, A2, A3, A extends any[], R>(this: (this: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3): (...args: A) => R;
bind<T, AX, R>(this: (this: T, ...args: AX[]) => R, thisArg: T, ...args: AX[]): (...args: AX[]) => R;
function sorting<T>(a: T, fn: (v0: T, v1: T) => number,  b: T) {
return fn(a, b)
}
sorting<number>.bind(null, 1, (a, b) => a + b)
//               ^ Cannot find name 'bind'.(2304)
sorting.bind<null, number, (v0: number, v1: number) => number, [b: number]>(null, 1, (a, b) => a + b)
//^ Argument of type '(b: number) => unknown' is not assignable to parameter of type //'(v0: number, v1: number) => number'.
//  Type 'unknown' is not assignable to type 'number'.(2345)

TS操场

它仍然不起作用。我遗漏了什么吗?为什么我不能用bind论证afn?


注:

目前我使用箭头函数来curry排序函数作为解决方法。

这实际上是一个常见的问题,而且非常常见,它将在TypeScript的下一个小版本(4.7)中修复!正在使用的解决方案称为实例化表达式。

下面是他们的例子:

interface Box<T> {
value: T;
}
function makeBox<T>(value: T) {
return { value };
}

你可以这样做:

const makeStringBox = (value: string) => makeBox(value); // makeBox<string>(value: string)

非常浪费,所以4.7引入了新的语法:

const makeStringBox = makeBox<string>; // type parameters passed without calling it!

这也意味着你可以在绑定它之前将它传递给sorting:

// works in 4.7+ now!
(sorting<number>).bind(null, 1, (a, b) => a + b)

你可以用这个例子试试TypeScript(4.8+)的夜间版本。

最新更新