Learning TypeScript 2.x
上QQ阅读APP看书,第一时间看更新

Functions with optional parameters

Unlike JavaScript, the TypeScript 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; 
} 

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 features optional parameters in functions to help us to increase the flexibility of our functions and overcome such scenarios.

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 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 optional parameters must always be located after the required parameters in the function's parameter list.