gpt4 book ai didi

typescript - 带有任意数量参数的函数,后跟 TypeScript 中的回调

转载 作者:行者123 更新时间:2023-12-04 10:12:11 27 4
gpt4 key购买 nike

我正在尝试为允许 string 的对象编写类型s 作为键和 function s 带有任意数量的参数,后跟作为值的回调。

// 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 library我可以使用它访问 Linux 的 DBUS api,并且我想为它的特定功能编写类型。

最佳答案

随着Variadic的发布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) => {});
Playground Link

关于typescript - 带有任意数量参数的函数,后跟 TypeScript 中的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61273834/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com