Wednesday, January 29, 2014

TypeScript: Allow any number of arguments

In JavaScript, functions don’t have a fixed signature and can be called with any number of arguments. Arguments that are not part of the function signature can be accessed through the arguments array(which actually isn’t a real array, but that’s another discussion).
But what if you want to build a similar functionality inside TypeScript? It took me some time to figure out how to get this working.
This functionality is supported through the ‘…’ rest parameter, an EcmaScript 6 proposal. This parameter collects any extra arguments passed to the function into a single named array:
Calling doSomething('a', 'b', 'c', 'd') would set argument a to a string 'a', argument b to a string ‘b’ and theArgs to be an array [ 'c', 'd' ].

No comments: