-
Notifications
You must be signed in to change notification settings - Fork 2
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
Optional assignment that creates keys if they dont exist #6
Comments
I don't believe it is, and your example can be one-lined today (if that what you're after) as follows: // An object containing optimized urls for `imageSrc` in various formats and resolutions
const manifest = {}
((manifest[imageSrc] ??= {})[format] ??= {})[width] = url |
I want to support this proposal and with this issue included. Use case is an object with an optional value of type object. As a simple example:
Right now the line must be instead e.g. So my enhancement proposal is that a left hand use (i.e. assignment) of an optional chaining does silently create an empty object. So that
is a short cut for
|
@ChristianMayer I disagree with your suggestion. As IMHO, it would imply too much magic. |
This gives me a decent idea for an alternative to the main use case. I'm sure others have found this before but I like it. (expr1??{}).prop = val Not as memory efficient but more DRY and readable than
|
Creating simple intermediate structure when it doesn't exist is a pretty common JS annoyance, and that was what I was assuming this proposal was at first (that is, I found it while looking to see if there was a proposal to solve that problem). Using the return from Short-circuiting the assignment when it doesn't exist seems very useful too though. It's too bad typescript makes use of |
But the autocreation of fields and objects with type A = {
a?: { c: string };
}:
let a: A = {} as any;
a.a!.c = 'hi'; // it compiles
a.a.c = 'hi'; // it does not compile |
I'm curious if the following pattern is something this proposal will consider within scope.
Relevant: lodash's utility:
The text was updated successfully, but these errors were encountered: