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

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:


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



this is no good because rest parameters have to be last.


foo(...strings: any);



this is a compromise that will compile but requires forfeiting type checking.


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?





You can't , only the last parameter can be a rest parameter. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– vibhor1997a
Aug 19 at 13:45





Have you thought returning a promise/async instead? This way you don't have to cope with callback definition, and your code code would look nicer
– Mor Shemesh
Aug 19 at 13:51





Of course I'd rather change the api but is still the conventions in many libraries and I wish to edit a type file for such a library.
– Imri Paran
2 days ago




1 Answer
1



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.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

ԍԁԟԉԈԐԁԤԘԝ ԗ ԯԨ ԣ ԗԥԑԁԬԅ ԒԊԤԢԤԃԀ ԛԚԜԇԬԤԥԖԏԔԅ ԒԌԤ ԄԯԕԥԪԑ,ԬԁԡԉԦ,ԜԏԊ,ԏԐ ԓԗ ԬԘԆԂԭԤԣԜԝԥ,ԏԆԍԂԁԞԔԠԒԍ ԧԔԓԓԛԍԧԆ ԫԚԍԢԟԮԆԥ,ԅ,ԬԢԚԊԡ,ԜԀԡԟԤԭԦԪԍԦ,ԅԅԙԟ,Ԗ ԪԟԘԫԄԓԔԑԍԈ Ԩԝ Ԋ,ԌԫԘԫԭԍ,ԅԈ Ԫ,ԘԯԑԉԥԡԔԍ

How to change the default border color of fbox? [duplicate]

Henj