Issue
I'd like to write a function that takes an object argument, uses destructuring in the function signature, and have that argument be optional:
myFunction({opt1, opt2}?: {opt1?: boolean, opt2?: boolean})
However, Typescript doesn't let me ("A binding pattern parameter cannot be optional in an implementation signature.").
Of course I could do it if I didn't destructure:
myFunction(options?: {opt1?: boolean, opt2?: boolean}) {
const opt1 = options.opt1;
const opt2 = options.opt1;
...
It seems like these should be the same thing, yet the top example is not allowed.
I'd like to use a destructured syntax (1) because it exists, and is a nice syntax, and it seems natural that the two functions above should act the same, and (2) because I also want a concise way to specify defaults:
myFunction({opt1, opt2 = true}?: {opt1?: boolean, opt2?: boolean})
Without destructuring, I have to bury these defaults in the implementation of the function, or have an argument that is actually some class with a constructor...
Solution
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();
Answered By - David Sherret
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.