Parameters are a core part of the type checking applied by the TypeScript compiler. TypeScript offers an optional functionality by adding the ? symbol as a postfix to the parameter name we want to make optional. This allows us to leave out the second parameter in the function call.
function greetMe(name: string, greeting?: string): string {
console.log(greeting);
if(!greeting) { greeting = 'Hello'; }
return greeting + ', ' + name;
}
console.log( greetMe('Chris') );
This code will attempt to print out the greeting variable as well as produce a proper greeting. Running this code like this:
greetMe('Chris');
Will give us the following result:
undefined
Hello Chris
So, an optional parameter doesn't really get set unless you explicitly make it so. It is more of a construct so that you can get help with deciding what parameters are mandatory and which ones are optional. Let's exemplify that:
function add(mandatory: string, optional?: number) {}
You can invoke this function in the following ways:
add('some string');
add('some string', 3.14);
Both versions are allowed. Using optional parameters in your function signature forces you to place them last, like the previous example. The following example illustrates what not to do:
function add(optional?: number, mandatory: string) {}
This would create a situation where both parameters would be mandatory:
add(11); // error. mandatory parameter missing
Even the compiler would complain and say the following:
A required parameter cannot follow an optional parameter
Remember, optionals are great, but place them last.