-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Support non-null assertion for destructuring #17390
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
Could be achieved with (or with better typings): let {
bar: {
bia,
pia = 0,
} = {} as Record<string, any> // Or Partial<Bar> if we have a Bar type,
} = foo; What's bothering me, is that we have to have an explicit type assertion on the default value in order to being able to destruct it. It would be better if the default-value type would be inferred to be Partial, or other - destructuring supporting - type. |
General opinion from the design meeting was that the destructuring syntax is already overly complex and hard to follow, so we'd prefer to not add any new syntax there unless it's absolutely necessary. |
Hey guys, it's been a few years on this one. I understand the original opinion that the destructuring syntax is complex. However, I believe the syntax is now hardened and solidified such that it's not going anywhere and is best practice. I think TypeScript should affirm that best practice with type checking. As it is, we resort to much more complex patterns due to the lack of this feature. interface Office {
company: {
name : string;
industry?: string;
address?: {
street: string;
city: string;
}
}
}
// How it should be
function doOffice(office: Office) {
const { company: { name, industry, address?: { street, city } } } = office;
...
// explicit null checks
if (!street || !city) {
//do something
}
}
// How it is now
function doOffice(office: Office) {
const { company: { name, industry, address } } = office;
if (!address) {
//do something
}
const { street, city } = address;
} As objects grow in complexity, this becomes tedious and very hard to read. Thanks for considering TS team! |
@RyanCavanaugh sorry for bumping old thread, but i just encountered same situation and i agree with @isaiahtaylorhh , and, guessing from all these upvotes, same goes for plenty of people also i don't think "becoming too complex" is valid reason not to do it, because that will only mean stagnation of the tool |
Please reconsider.
becomes useless, if i have to check it for null, or need an extra line. |
Currently if we want to retrieve a value nested inside a nullable property using destructuring, we have to split a single destructuring statement into two even if we know that the nullable property would always be non-null in under that branch.
For example:
The text was updated successfully, but these errors were encountered: