簡體   English   中英

在 TypeScript 中以嚴格模式傳遞給定回調函數中的其余參數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM