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, ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.