Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript declaration file for function with variable number/type of arguments

headjs does some very crazy JavaScript type things to its API. For instance it takes an arbitrary number of strings (not a string array) for a function. Sometimes it ends that same function call, you can optionally end it with a function, for example.

head.js("scripturl1", "scripturl2",...,callback); 

You can also (just as easily) do the following

head.js({scriptlabel:"scripturl1"},{scriptlabel2:"scripturl2"},...., callback); 

My question is how the HECK do we describe that in a declaration file? I am all ears here as my current pass seems completely wrong.

like image 339
Josh Handel Avatar asked Oct 16 '12 03:10

Josh Handel


People also ask

How do you pass variable number of arguments in TypeScript?

The TypeScript / ECMAScript 6 Waylet varArgs = (... args: string[]) => { console. log(... args); };

How do you declare a variable of type number in TypeScript?

The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable.

How do you declare arguments in TypeScript?

We can declare it by prefixing the three "dot" characters ('...') before the parameter. It allows the functions to have a different number of arguments without using the arguments object.


1 Answers

The TS language spec refers to variable number/spread parameters as "Rest Parameters". An example interface with a function signature that accepts rest params:

interface IExample {     fn : (...args : any[]) => any; }  var x : IExample = {     fn: function(...args : any[]) {         for (var i = 0, arg; arg = args[i]; i++) {             console.log(arg);         }     } }  x.fn(1); x.fn(1, 2); x.fn("cat", "dog", "mouse"); 

Unfortunately, there are some limitations. The "Rest Parameter" has to be the last one in a function's signature -- so you won't be able to capture the type of the callback parameter since it is after the repeating parameter.

If it wasn't, you would have been able to do something like this:

var fn = function(cb: Function, ...args : string[]) {     ... } 
like image 136
nxn Avatar answered Oct 06 '22 10:10

nxn