9

I would like to declare a function which last parameter is always a callback. However when i do:

interface Statement extends events.EventEmitter {
    bind(...args, callback?:(err?:Error)=>void) : Statement;
}

I get an error

error TS1014: Rest parameter must be last in list

Is it possible in typescript to heve Rest parameter not as a last param in the argument list? Is there any hack that could help me solve this problem?

3 Answers 3

19

While a rest parameter needs to be the last one, you can now use variadic tuple types in TS 4.0:

type VarCallback<T extends any[]> = (...args: [...T, (err?: Error) => void]) => void

VarCallback ensures, the last function parameter is a callback type (err?: Error) => void.

For example, declare a function type with the first two parameters string and number:

type MyCallback = VarCallback<[string, number]>
// (a1: string, a2: number, a3: (err?: Error | undefined) => void) => void

const myCb: MyCallback = (s, n, cb) => {/* your implementation */ }
// s,n,cb are strongly typed now

Live code sample

6

This isn't supported in TypeScript. The best you can do is ...args: any[], or only use libraries with more sensible parameter orderings.

2
  • I know it's a long shot, but with all the changes since Feb 2014, is there perhaps a better way to hack this together now? The folks at RxJS are using methods where they need to accept a variable number of observables as the first set of arguments, and an optional final argument of a different type (here's one example). Would variadic kinds perhaps help here? Jan 12, 2016 at 12:26
  • Now you could use a union type for the rest arg e.g. function foo(first: string, ...middleNumberAndFinalBoolean: Array<number|boolean>). This is somewhat safer than any. Jan 12, 2016 at 17:54
2

The TypeScript spec for the rest parameter is aligned with ES6's: it is the last arg in the param list. You should change your argument order.

from TypeScript Language Spec (#Parameter List):

A signature’s parameter list consists of zero or more required parameters, followed by zero or more optional parameters, finally followed by an optional rest parameter.

from ES6: rest parameters - Semantics:

The last parameter in the [[FormalParameters]] List is used for the rest parameter. Of the standard built-in ECMAScript objects, only Function objects implement [[HasRestParameters]].

1
  • 20
    "You should change your argument order." -- Good luck with that. Writing declarations for Node libraries, where the callback is always last? That's probably thousands of libraries that need to be rewritten... Oct 13, 2017 at 20:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.