support optional paramter on arrow function

Topics: Language Specification
Oct 4, 2012 at 2:59 AM

As for the JavaScript, ignore argument is general.
As well as overload, please add better support of the argument abbreviation with the optional paramter.

function each(source: any[], action: (value: any, index?: number) => void ) {
    for (var i = 0; i < length; i++) {
        action(source[i], i);
    }
}

// valid
each([1, 2, 3, 4, 5], x => console.log(x));

// invalid, but I expect this works
each([1, 2, 3, 4, 5], (x, i) => console.log(i + ":" + x));

// valid
each([1, 2, 3, 4, 5], (x: any, i?: number) => console.log(i + ":" + x));

Developer
Oct 4, 2012 at 11:33 AM

Optional parameters rarely make sense with callbacks because they state that the call to the callback may or may not supply that parameter. Since the call to the callback will presumably always supply all the parameters, you should declare them as regular parameters. You are still free to omit parameters in the actual implementations of the callback. Intuitively, it is safe to ignore parameters, but it is not safe to expect parameters that may not be supplied (as is the case in your invalid example).

Here's an example that works:

function each(source: any[], action: (value: any, index: number) => void) {
    for (var i = 0; i < length; i++) {
        action(source[i], i);
    }
}

// valid
each([1, 2, 3, 4, 5], x => console.log(x));

// also valid
each([1, 2, 3, 4, 5], (x, i) => console.log(i + ":" + x));