Can you have optional destructured arguments in a Typescript function?
Use a default parameter instead:
function myFunction({ opt1, opt2 = true }: { opt1?: boolean; opt2?: boolean; } = {}) {
console.log(opt2);
}
myFunction(); // outputs: true
It's necessary in order to not destructure undefined
:
function myFunction({ opt1, opt2 }) {
}
// Uncaught TypeError: Cannot destructure property `opt1` of 'undefined' or 'null'.
myFunction();
You can't destructure if there is not an object given as an argument. Therefore use a default object in the parmas as the previous post mentioned:
type Options = { opt1?: boolean; opt2?: boolean; }
function myFunction({ opt1, opt2 }: Options = {}) {
console.log(opt2, opt1);
}
myFunction() // undefined, undefined
myFunction({opt1: false}); // undefined, false
myFunction({opt2: true}); // true, undefined
What I would like to add is that this destructuring pattern in the params adds the most value when the following 2 conditions hold:
- The amount of options is likely to change
- There could potentially be change in API of the function. i.e. the function params are likely to change
Basically destructuring gives you more flexibility since you can add as many options as you like with minimal change to the function's API.
However, the more basic version would be simpler:
// If the function is not likely to change often just keep it basic:
function myFunctionBasic( opt1? :boolean, opt2?: boolean ) {
console.log(opt2, opt1);
}