I stumbled upon the following typescript function while inspecting the content metadata component of Alfresco ADF and I can't make sense of it:
private saveNode({ changed: nodeBody }): Observable<Node> {
return this.nodesApiService.updateNode(this.node.id, nodeBody);
}
What I don't understand is the { changed: nodeBody }
.
According to this and this answer, the curly braces are used to denote an object literal as a way to use a key/value pair as a function argument. But here it is used as a parameter. If this creates an object, in my understanding, that would mean that changed
is the name of its property and nodeBody
refers to the properties value. But which variable is this object assigned to and how can you refer to it in the method body?
What confuses me even more is that only nodeBody
is used in the return statement. Then why isn't it used right away as a single parameter?
What is the benefit or use-case of this form of input?
Curly braces { } are special syntax in JSX. It is used to evaluate a JavaScript expression during compilation. A JavaScript expression can be a variable, function, an object, or any code that resolves into a value. Let's take an example.
In languages like C curly braces ( {} ) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks. Save this answer.
Curly braces - { } One of the biggest differences between Python and other popular programming languages is that in Python, curly braces are not used to create program blocks for flow control. In Python, indentation is used for flow control, which makes Python much easier to read than most other programming languages.
Curly braces in javascript are used as shorthand to create objects. For example: // Create an object with a key "name" initialized to the value "testing" var test = { name : "testing" }; alert(test.
Your understanding is correct.
The way I see it, there are two main benefits to using that approach, the first one is the obvious type safety that you get by specifying that your function can only accept parameters with a certain shape.
function f({ a: b }) {
return b;
}
f({a: 1}) // -> 1
f({c: 1}) // type error
The second thing is simply the convenience of not having to explicitly type a.b
(changed.nodeBody
in your case) multiple types in the body of the function. In your example you only use nodeBody
once in the return statement, but you can easily imagine a situation where that value is used multiple times.
But which variable is this object assigned to and how can you refer to it in the method body?
In your example, you can simply use nodeBody
in the body of the function to refer to the value of the changed
key of the parameter object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With