Optional and Default Function Parameters in TypeScript
In a function, we can specify optional parameters by using a question mark (?). An optional parameter by be good if passing in this parameter is optional, meaning it can be null or undefined. Sometimes we can do different things as well based on if this parameter was passed in or not.
Here is an example of an optional parameter for a function in TypeScript:
// b is an optional parameter
function addTwoValues(a: number, b?: number) {
}
As you can see, b is equal to an optional parameter because it is specified with a (?) question mark. This means that when passing values into the addTwoValues function, only 1 is needed:
// b is an optional parameter
function addTwoValues(a: number, b?: number) {
console.log('a: ', a);
console.log('b: ', b);
}
addTwoValues(1);
// a: 1
// b: undefined
When the value is not passed in, it will equal undefined.
Optional parameters are great, because we can do different things based on whether a value is passed in or not:
// b is an optional parameter
function addTwoValues(a: number, b?: number) {
// If b is not given, we can just return a by itself;
if(!b) return a;
// If b is given, we can add and return both a + b;
return a + b;
}
We can also give b a default value if it is not passed in as well! A default parameter is basically saying we’d like to assign it this value if for some reason nothing for this parameter is passed in:
// b is assigned 0 if no value is passed in
function addTwoValues(a: number, b: number = 0) {
return a + b;
}
addTwoValues(2); // returns 2 + 0
To spice things up a bit, we could assign b to null as well, making it a true optional value:
// b is assigned null if no value is passed in
// only a number or null can be passed into b
function addTwoValues(a: number, b: number | null = null) {
if(!b) return a;
return a + b;
}
Now b can only be null if no number is passed into this function for b.
Thanks for reading! 😎