[SOLVED] Typescript: Curly braces as function parameter


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?


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.

Answered By – bugs

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *