我已經撰寫了一個排序函式,并想將一個比較函式系結到它。不幸的是,TypeScript 編譯器警告我unknown
比較函式的型別。
我試過搜索SO: Bind function to function and search in TS Handbook: 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
為什么我不能a
和fn
?
附言
目前我使用箭頭函式將排序函式作為一種解決方法。
uj5u.com熱心網友回復:
這實際上是一個常見問題,并且非常普遍,以至于它正在 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 ) 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477875.html
上一篇:Fizz企業級微服務API網關進階系列教程-服務編排處理串列資料(上)-展開與合并
下一篇:介面中的Java實作類