Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript rest parameter in the middle of arguments list

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?

like image 641
Szymon Wygnański Avatar asked Feb 26 '14 13:02

Szymon Wygnański


3 Answers

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

like image 102
bela53 Avatar answered Sep 27 '22 16:09

bela53


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

like image 24
Ryan Cavanaugh Avatar answered Sep 27 '22 16:09

Ryan Cavanaugh


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]].

like image 26
deck Avatar answered Sep 27 '22 16:09

deck