Typescript - 将函数及其参数传递给另一个函数&强制执行参数的数量和类型
我想定义一个函数,该函数获取另一个函数 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可以使用 参数 实用程序类型来完成此操作。
例如...
这里是一个游乐场,显示您预期的错误。
请注意,此检查仅在编译时进行,在 TypeScript 编译为 JavaScript 后不会提供任何运行时保护。如果您需要运行时保护,则需要使用 参数< /a> 对象并编写一些自定义代码来验证传递的参数的数量和类型。像这个之类的东西。
Can do that using the Parameters utility type.
For example...
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.