简体   繁体   English

如何在TypeScript中的rest参数之后指定回调函数?

[英]How do I specify a callback function after rest parameters in TypeScript?

I have a function that receives an some arbitrary number of strings like in this example: 我有一个函数可以接收任意数量的字符串,例如本例:

function foo(...strings, callback);

How do I specify it's types in typescript? 如何在打字稿中指定其类型? I weighed the following alternatives: 我权衡了以下替代方案:

  1. functio foo(...strings: string, callback: (err: Error, res: any) => void);

this is no good because rest parameters have to be last. 这不好,因为rest参数必须是最后一个。

  1. foo(...strings: any);

this is a compromise that will compile but requires forfeiting type checking. 这是一个可以编译的折衷方案,但需要放弃类型检查。

  1. foo(...strings: string|((err: Error, res: any) => void));

this is a bit more true but is very non-readable and I don't think I saw it in any project. 这有点真实,但是非常难以理解,我认为我在任何项目中都没有看到它。

Is there a best practice to deal with this? 是否有最佳实践来应对? What trade offs should be taken into account? 应该考虑哪些权衡?

This is not possible, you have to change your 'order style', and put your callback before your rest parameters. 这是不可能的,您必须更改“订单样式”,并将回调函数放在其余参数之前。 That would be a better (more readable and more type safe) solution than the other awkward workarounds you listed. 与您列出的其他笨拙的解决方法相比,这将是一个更好的解决方案(更具可读性和类型安全)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM