TypeScript Functions Optional Parameters – Default And REST

TypeScript Optional Parameters

Unlike JavaScript, the TypeScript Optional Parameters compiler will throw an error if we attempt to invoke a function without providing the exact number and types of parameters that its signature declares. Let’s look at a code sample to demonstrate this:

function add(foo: number, bar: number, foobar: number): number { 
    return foo + bar + foobar; 
} 

Typescript Optional Function Parameters

The preceding function is called add and will take three numbers as parameters, named foo, bar, and foobar. If we attempt to invoke this function without providing exactly three numbers, we will get a compilation error indicating that the supplied parameters do not match the function’s signature:

add(); // Error, expected 3 arguments, but got 0. 
add(2, 2); // Error, expected 3 arguments, but got 2. 
add(2, 2, 2); // OK, returns 6 

There are scenarios in which we might want to be able to call the function without providing all its arguments. TypeScript optional parameters functions features help us to increase the flexibility of our functions and overcome such scenarios.

Typescript Named Parameters

We can indicate to the TypeScript compiler that we want a function’s parameter to be optional by appending the ? character to its name. Let’s update the previous function to transform the required foobar parameter into an typescript optional parameter:

function add(foo: number, bar: number, foobar?: number): number { 
    let result = foo + bar; 
    if (foobar !== undefined) { 
        result += foobar; 
    } 
    return result; 
} 

Note how we have changed the foobar parameter name to foobar?, and how we are checking the type of foobar inside the function to identify whether the parameter was supplied as an argument to the function or not. After implementing these changes, the TypeScript compiler will allow us to invoke the function without errors when we supply two or three arguments to it:

add(); // Error, expected 2-3 arguments, but got 0. 
add(2, 2); // OK, returns 4 
add(2, 2, 2); // OK, returns 6 

It is important to note that the typescript optional parameters must always be located after the required parameters in the function’s parameter list.

TypeScript Functions Defaut Parameters

When a typescript function has some optional parameters, we must check whether an argument has been passed to the function (just like we did in the previous example) to prevent potential errors.

There are some scenarios where it would be more useful to provide a default value for a parameter when it is not supplied than making it an optional parameter. Let’s rewrite the add function (from the previous section) using the inline if structure:

function add(foo: number, bar: number, foobar?: number): number { 
    return foo + bar + (foobar !== undefined ? foobar : 0); 
} 

There is nothing wrong with the preceding function, but we can improve its readability by providing a default value for the foobar parameter instead of using an optional parameter:

typescript optional parameters with default value

function add(foo: number, bar: number, foobar: number = 0): number { 
    return foo + bar + foobar; 
} 

To indicate that a function parameter is optional, we need to provide a default value using the = operator when declaring the function’s signature. After compiling the preceding code examples, the TypeScript compiler will generate an if structure in the JavaScript output to set a default value for the foobar parameter if it is not passed as an argument to the function:

function add(foo, bar, foobar) { 
    if (foobar === void 0) { foobar = 0; } 
    return foo + bar + foobar; 
} 

This is great because the TypeScript compiler generated the code necessary for us to prevent potential runtime errors.

The void 0 parameter is used by the TypeScript compiler to check whether a variable is undefined. While most developers use the undefined variable to perform this kind of check, most compilers use void 0 because it will always evaluate as undefined. Checking against an undefined variable is less secure because its value could have been modified, as demonstrated by the following code snippet:

function test() {
     var undefined = 2; // 2
     console.log(undefined === 2); // true
 }

Just like typescript optional parameters, default parameters must always be located after any required parameters in the function’s parameter list.

TypeScript Functions REST Parameters

We have learned how to use typescript optional and default parameters to increase the number of ways that we can invoke a function. Let’s return one more time to the previous example:

function add(foo: number, bar: number, foobar: number = 0): number { 
    return foo + bar + foobar; 
} 

We have learned how to invoke the add function with two or three parameters, but what if we wanted to allow other developers to pass four or five parameters to our function? We would have to add two extra default or optional parameters. And what if we wanted to allow them to pass as many parameters as they need? The solution to this possible scenario is the use of REST parameters. The REST parameter syntax allows us to represent an indefinite number of arguments as an array:

function add(...foo: number[]): number { 
let result = 0;
for (let i = 0; i < foo.length; i++) {
result += foo[i];
}
return result; }

As we can see in the preceding code snippet, we have replaced the function parameters foo, bar, and foobar with just one parameter named foo. Note that the name of the parameter foo is preceded by an ellipsis (a set of three periods—not the actual ellipsis character). A Typescript REST parameter must be of an array type or we will get a compilation error. We can now invoke the add function with as many parameters as we need:

add(); // 0  
add(2); // 2
add(2, 2); // 4
add(2, 2, 2); // 6
add(2, 2, 2, 2); // 8
add(2, 2, 2, 2, 2); // 10
add(2, 2, 2, 2, 2, 2); // 12

Although there is no specific limit to the theoretical maximum number of arguments that a function can take, there are, of course, practical limits. These limits are entirely implementation-dependent and, most likely, will also depend on exactly how we are calling the function.

JavaScript functions have a built-in object called the arguments object. This object is available as a local variable named arguments. The arguments variable contains an object like an array that contains the arguments used when the function was invoked.

The arguments object exposes some of the methods and properties provided by a standard array, but not all of them. Refer to the documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments to learn more about its peculiarities.

If we examine the JavaScript output, we will notice that TypeScript iterates the arguments object to add the values to the foo variable:

function add() { 
    var foo = []; 
    for (var _i = 0; _i < arguments.length; _i++) { 
        foo[_i - 0] = arguments[_i]; 
    } 
    var result = 0; 
    for (var i = 0; i < foo.length; i++) { 
        result += foo[i]; 
    } 
    return result; 
} 

We can argue that this is an extra, unnecessary iteration over the TypeScript function’s parameters. Even though it is hard to imagine this extra iteration becoming a performance issue, if you think that this could be a problem for the performance of your application, you may want to consider avoiding the use of TypeScript REST parameters and use an array as the only parameter of the TypeScript function instead:

function add(foo: number[]): number { 
    let result = 0; 
    for (let i = 0; i < foo.length; i++) { 
        result += foo[i]; 
    } 
    return result; 
} 

The preceding TypeScript function takes an array of numbers as its only parameter. The invocation API will be a little bit different from the TypeScript REST parameters, but we will effectively avoid the extra iteration over the function’s argument list:

add(); // Error, expected 1 arguments, but got 0. 
add(2); // Error, '2' is not assignable to parameter of type 'number[]'. 
add(2, 2); // Error, expected 1 arguments, but got 2. 
add(2, 2, 2); // Error, expected 1 arguments, but got 3. 
 
add([]); // returns 0 
add([2]); // returns 2 
add([2, 2]); // returns 4 
add([2, 2, 2]); // returns 6 

Keywords:

TypeScript Optional Parameters,Typescript Optional Function Parameters,Typescript Named Parameters,TypeScript Functions Defaut Parameters,typescript optional parameters with default value,TypeScript Functions REST Parameters.