Typescript - 将函数及其参数传递给另一个函数&强制执行参数的数量和类型

发布于 2025-01-16 20:07:25 字数 639 浏览 1 评论 0原文

我想定义一个函数,该函数获取另一个函数 f 及其参数 args 作为参数,并且我希望 Typescript 确保传递的参数对于传递的函数是正确的。

伪代码

function A (n: number, s: string, b: boolean) {
  ...
}

function B (f: Function, ...args: typeof arguments of f) {
  ...
  f(args)
}

B(A, 1, 'str', true) // typescript is happy
B(A, 1, 'str') // typescript is sad
B(A, 1, undefined, true) // typescript is sad
// any other example of wrong arguments of A passed to b would raise Typescript error...

所以这里重要的部分是:

...args: typeof arguments of f

这显然是无效有效的Typescript。

我怎样才能编写打字稿代码来做到这一点?

I want to define a function that gets as parameters another function f and its arguments args, and I want Typescript to make sure that the passed arguments are correct for the passed function.

Pseudo code

function A (n: number, s: string, b: boolean) {
  ...
}

function B (f: Function, ...args: typeof arguments of f) {
  ...
  f(args)
}

B(A, 1, 'str', true) // typescript is happy
B(A, 1, 'str') // typescript is sad
B(A, 1, undefined, true) // typescript is sad
// any other example of wrong arguments of A passed to b would raise Typescript error...

So the important part here is this:

...args: typeof arguments of f

Which is obviously not valid Typescript.

How can I write typescript code that does that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我们的影子 2025-01-23 20:07:26

可以使用 参数 实用程序类型来完成此操作。

例如...

function B<T extends (...args: any) => any> (f: T, ...args: Parameters<T>) {
  f(args)
}

这里是一个游乐场,显示您预期的错误。

请注意,此检查仅在编译时进行,在 TypeScript 编译为 JavaScript 后不会提供任何运行时保护。如果您需要运行时保护,则需要使用 参数< /a> 对象并编写一些自定义代码来验证传递的参数的数量和类型。像这个之类的东西。

Can do that using the Parameters utility type.

For example...

function B<T extends (...args: any) => any> (f: T, ...args: Parameters<T>) {
  f(args)
}

Here is a playground showing the errors you are expecting.

Note that this checking is compile time only and will not provide any runtime protection after the TypeScript is compiles to JavaScript. If you need runtime protection you need to use the arguments object and write some custom code to verify number and types of arguments passed. Something like this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文