Description
Extracting this suggestion from this issue:
#1336
Currently the variable arguments list supports variable arguments only as the last argument to the function:
function foo(arg1: number, ...arg2: string[]) {
}
This compiles to the following javascript:
function foo(arg1) {
var arg2 = [];
for (var _i = 1; _i < arguments.length; _i++) {
arg2[_i - 1] = arguments[_i];
}
}
However, variable argument functions are limited to appearing only as the last argument and not the first argument. I propose support be added for having a variable argument appear first, followed by one or more fixed arguments:
function subscribe(...events: string[], callback: (message: string) => void) {
}
// the following would compile
subscribe(message => alert(message)); // gets all messages
subscribe('errorMessages', message => alert(message));
subscribe(
'errorMessages',
'customMessageTypeFoo123',
(message: string) => {
alert(message);
});
// the following would not compile
subscribe(); // supplied parameters do not match any signature of call target
subscribe('a1'); // argument of type 'string' does not match parameter of type '(message: string) => void'
subscribe('a1', 'a2'); // argument of type 'string' does not match parameter of type '(message: string) => void'
subscribe compiles to the following JavaScript:
function subscribe() {
var events= [];
var callback = arguments[arguments.length - 1];
for(var _i = 0; _i < arguments.length - 2; _i++) {
events[_i] = arguments[_i];
}
}
notes: it should be impossible for typescript code to call this function with zero arguments when typechecking. If JS or untyped TS code calls it without arguments, callback will be undefined. However, the same is true of fixed arguments at the beginning of the function.
edit: used a more realistic/motivating example for the fixed-last/variable-arguments-first function.