Either Array or undefined or default array as argument to function

Viewed 127

I want to pass optionally an array to a function or an array setting it to a default value.

This is the typical way: function myfunc(...values : Array<number>)

I know that I can do it this way, but I don't know how to set it to allow this function calls:

myfunc()
myfunc(1)
myfunc(1,2)
myfunc([1, 2])

with the above, all except myfunc() are supported. How can I make it?

3 Answers

Here it is:

function myfunc(...values : Array<number> | [Array<number>]) {}

myfunc()
myfunc(1)
myfunc(1,2)
myfunc([1, 2])

myfunc('invalid')
myfunc([1, 2], [3, 4])

Here is a preview where you can check the result.

You can define your two overloads and then specify the logic in a single function. Something like below should work.

function myfunc(...values : Array<number>): number;
function myfunc(values : Array<number>): number;

function myfunc(value : (Array<number> | number), ...values : Array<number>): number {
    if (typeof value === 'number') {
        values.unshift(value);
    } else if (value === undefined) {
        values = [];
    } else {
        values = value;
    }

    // logic

    return values.length;
}

myfunc(); // correct
myfunc(1); // correct
myfunc(1, 2); // correct
myfunc([1, 2]); // correct
myfunc(1, 2, 3, 4); // correct
myfunc([1, 2, 3]); // correct
// myfunc([1, 2, 3, 4], 5, 6); // error
// myfunc([1, 2], [3, 4]); // error

console.log(myfunc(1, 2, 3)) // 3
console.log(myfunc([1, 2, 3])) // 3

Notice how because we have not defined an interface for an array followed by values, the final example results in an error which I think is the expected behaviour. An example can be seen here. We have to check for undefined here as the transpiled JavaScript does not take into account the different function overloads, and instead provides a single implementation where value can be undefined.

Can you use like this in a simple way !!!

function a(k = []) {
    console.log(k)
}

a();
a(1);
a([1]);
a([1, 2, 3]);
Related