網站搜尋

在 TypeScript 中具有任意數量參數且後跟回調函數的函數


我正在嘗試為一個對象編寫一種類型,該對象允許使用 string 作為鍵,使用任意數量參數的 function,其後跟一個回調作為值。

// non working dummy code
type MyObject = Record<string, (...args: any[], callback(err: Error, result: any)>

// so that I can do this
const myObject = {
  foo: ((err, result) => {}),
  bar: ("arg", (err, result) => {}),
  baz: ("other", "args", true, 12, (err, result) => {}),
}

這件事的背景是我正在使用 dbus npm 庫,通過它我可以訪問 Linux 的 DBUS API,我想為它的特定函數編寫類型。

答案#1

隨著 v4.0 中可變元組的發布,你現在可以這樣做:

declare function foo<T extends any[], R>(...args: [...T, (err: Error, result: R) => any]): any;

foo((err, result: string) => {});

foo("args", (err, result: string) => {});
 
foo("other", "args", true, 12, (err, result: string) => {});

遊樂場連結

答案#2

變長參數必須位於函數簽名的最後。

type MyObject = Record<string, (callback(err: Error, result: any), ...args: any[])>

const myObject = {
  foo: ((err, result) => {}),
  bar: ((err, result) => {}, "arg"),
  baz: ((err, result) => {}, "other", "args", true, 12),
}