![](/img/trans.png)
[英]How to pass arguments to callback in React + Typescript without new function creation?
[英]Pass rest of arguments in a given callback function in TypeScript in strict mode
我有一個函數A
將另一個函數作為參數。 在函數A
內部,我想使用一個顯式參數執行給定函數,並使用函數的給定參數。 像這樣。
function t(g: number, p: any, b: any): void {
console.log(g)
console.log(p)
console.log(b)
}
function execute(fn: (t: number, ...args: any[]) => void) {
// But this is not working...getting this error --- 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
const ar = fn.arguments.slice(1)
fn(3, ...ar)
}
execute(t)
如何在嚴格模式下捕獲使用fn
執行的args
?
除了您使用的是嚴格模式之外,在這里使用fn.arguments
沒有任何意義,因為fn
沒有被傳遞任何參數。 相反,您可以添加一個args
參數來execute
並將它們傳遞給fn
。
function t(g: number, p: any, b: any): void {
console.log(g);
console.log(p);
console.log(b);
}
function execute<TRestArgs extends any[]>(fn: (g: number, ...args: TRestArgs) => void, ...args: TRestArgs) {
fn(3, ...args);
}
execute(t, "p", "b");
我添加了TRestArgs
類型參數以提供類型安全。 現在execute(t, "p", "b", "x")
將引發錯誤,因為t
只有三個參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.