Using curly braces as function parameters in Typescript

While exploring the content metadata component of Alfresco ADF, I came across this typescript function that has left me puzzled:

private saveNode({ changed: nodeBody }): Observable<Node> {
  return this.nodesApiService.updateNode(this.node.id, nodeBody);
}

I'm struggling to make sense of the { changed: nodeBody }.

Based on explanations from sources like this and this, it seems that the curly braces are being used to define an object literal as a way to pass key/value pairs as function arguments. However, in this case, it's being used as a parameter. If this construct indeed creates an object, my understanding is that changed would be the property name and nodeBody would be its value. But how is this object assigned to a variable and how can it be referenced within the method body?

Adding to my confusion is the fact that only nodeBody is utilized in the return statement. So why isn't it simply used as a single parameter right away?

What exactly is the purpose or benefit of using this particular input format?

Answer №1

Your interpretation is spot on.

There are two key advantages to utilizing this approach. Firstly, it provides type safety by specifying that your function can only accept parameters with a defined structure.

function f({ a: b }) {
  return b;
}

f({a: 1}) // -> 1
f({c: 1}) // type error

The second benefit is the ease of not having to repeatedly declare a.b (changed.nodeBody in this case) various times within the function body. While you may only use nodeBody once in the return statement as shown in your example, there could be scenarios where this value is utilized multiple times.

However, how do you assign this object to a variable and reference it within the method?

In the context of your example, you can simply utilize nodeBody within the function to access the value stored in the changed property of the parameter object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 17 presents a unique challenge regarding APP_INITIALIZER and Server-Side Rendering (

Hello everyone, I've run into an issue while attempting to transition to SSR in Angular 17 from my current client-only setup in Angular 16. I have two services in play - CiyuanEnvironmentService and LiveService. The LiveService relies on the environme ...

Updating the selected state of an Angular 2 material mat-chip

Attempting to update the selected property of a chip named "chip" results in an ExpressionChangedAfterItHasBeenCheckedError when changing the binding property. HTML <mat-chip-list> <mat-chip *ngFor="let w of weekDays" [selectable]="tru ...

The Google Sign-in feature is unable to access the property 'load' due to being undefined

I'm currently working on implementing a Google Sign-in feature in an Angular application, but I'm encountering the following error: Cannot read property 'load' of undefined This was actually working perfectly just an hour ago, but n ...

Is there a way to determine the quantity of lines within a div using a Vue3 watcher?

Is it feasible to determine the number of text lines in a div without line breaks? I am looking to dynamically display or hide my CTA link based on whether the text is less than or equal to the -webkit-line-clamp value: SCRIPT: const isExpanded = ref(true ...

Steps to resolve the issue of being unable to destructure property temperatureData from 'undefined' or 'null' in a React application without using a class component

CODE: const { temperatureData } = state; return ( <> <div className="flex flex-row"> {temperatureData.map((item, i) => ( <div className="flex flex-auto rounded justify-center items-center te ...

Having issues with Craco not recognizing alias configuration for TypeScript in Azure Pipeline webpack

I am encountering an issue with my ReactJs app that uses Craco, Webpack, and Typescript. While the application can run and build successfully locally, I am facing problems when trying to build it on Azure DevOps, specifically in creating aliases. azure ...

The const keyword is not automatically inferred as a const when using conditional types for generic type parameters

Within Typescript, the const modifier can be applied to function type parameters. This ensures that the inferred type matches the literal received with as const. function identity<const T>(a: T){ return a } For example, when using identity({ a: 4 ...

Add TypeScript typings for npm utility manually by incorporating type definitions

I'm in the process of incorporating TypeScript into an existing JavaScript project, and I'm currently facing the challenge of adding typings to an npm module that lacks type definitions, which I anticipate will be a common issue. When I try to i ...

Angular8 Chart.js customizes the Y axis tick labels

Is there a way to dynamically adjust the Y-axis ticks in a chart.js graph? I attempted to modify them using the following commands: this.chartOptions.scales.yAxes[0].ticks.min = 10; this.chartOptions.scales.yAxes[0].ticks.max = 18; ...

Steps to establish a maximum font size for my buttons

I've been working on creating buttons to decrease and increase the font size of my text. The functionality is there, but I want to establish a limit on how small or large the font can go. Here's what my current code looks like: <md-button ng ...

What is the most efficient way to use map-reduce in TypeScript to filter a list based on the maximum value of an attribute?

Recently, I came across a list that looked something like this: let scores = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}, {name: "D", skills: 60, ...

One parent contains two identical components, but the first component takes precedence over the second

Within my component, I have two subcomponents that are identical: <!-- Some code ... --> <app-upload-button #idBook [accept]="'image/*'" (loadend)="onImageLoaded('#this-idbook-preview')" > </app-upload-button> ...

`Observing a nearby external library while running the application`

I am currently working on a main app alongside some independent libraries. To incorporate changes from the library into the main app, I have been including the .tgz file in the main app's package.json. However, this process requires me to build and pa ...

TypeScript generic types allow you to create reusable components that

function genericIdentity<T>(arg: T): T { return arg; } let myGenericIdentity: <U>(arg: U) => U = genericIdentity; I see that the 'genericIdentity' function is accepting an argument of a generic type. However, I am unsure about ...

Navigating the structure of an Angular project: sorting modules by core, features, and

Before we begin, let me clarify that this question is original and has not been asked before. I have thoroughly reviewed the angular guide on this topic. However, I still find myself with a handful of questions. Starting with feature modules - the concept ...

How can I capture the click event on the oktext in Ionic?

When using Ionic, I have a select button with options for okText and cancelText. The issue I am facing is that when I click on okText, the menu closes as expected due to this attribute. However, I am interested in implementing it through click events. Belo ...

The modules 'MdCardModule' and 'MdTooltipModule' do not have any exported members

Encountering Errors After Running ng build Issue found in C:/761/search- bar/workload_management_app/Client/src/app/app.module.ts (8,9): Module '"C:/761/search- bar/workload_management_app/Client/node_modules/@angular/materia ...

Develop an asynchronous thunk with TypeScript in Redux Toolkit, utilizing the features of rejectWithValue and Payload types for handling errors

Struggling to integrate an authentication slice into Redux Toolkit using TypeScript, facing errors related to rejectWithValue and action payload types. Utilizing Axios and following the documentation, but TypeScript is still flagging issues in my code. im ...

Is it feasible to pre-render an Angular2 view invisibly when hovering?

Can a view be preloaded and prerendered invisibly upon hover? I have an application that displays a list of items. Each item is its own component, and when you click on any of these items, it is replaced by a detailed view (another component) of the same ...

Resolving the Angular NG0100 Error: Troubleshooting the ExpressionChangedAfterItHasBeenCheckedError

I am currently working on implementing a dialog component that takes in data through its constructor and then utilizes a role-based system to determine which parts of the component should be displayed. The component code snippet looks like this: export cl ...