-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Object destructuring fails if defaults are set #16355
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I think this is what you want. Object destructuring with type sometime really confuses people. function fancyMethod({ option1 = true, option2 = 1 }: { option1?: boolean, option2?: number } = {}) {
console.log(option1, option2);
}
fancyMethod();
fancyMethod({option2: 3}); |
Thanks I tried this but didn't use it because of #16354 The solution now is:
If you think of 5 options this becomes very very unreadable and creates maintenance overhead. Is there any chance to fix it so that the following will work?
|
This is not a valid TS code, since function fancyMethod({ option1: boolean = true, option2: number = 1 } = {}) { // <--
console.log(option1, option2);
} Additionally, I think you can use interface X {
option1?: boolean;
option2?: number;
}
type NonPrimitive<T> = object & T;
function fancyMethod(x: NonPrimitive<X> = {}) {
const {
option1 = true,
option2 = 1,
} = x;
console.log(option1, option2);
} |
Unfortunately the interface would be far away from the method as it is a class method. But thanks to your explanation with the renaming I am now understanding the reason behind it 👍 |
TypeScript Version: 2.2.1 / nightly (2.2.0-dev.201xxxxx)
Try it yourself in the playground
Code
Expected behavior:
Console log shows value of option1 and option 2
Actual behavior:
Typescript shows errors:
The text was updated successfully, but these errors were encountered: