Refreshing the sub attributes of an incomplete entity

My Partial object contains sub-properties that may be undefined and need updating.

interface Foo {
    data: string
    otherData: string
}
interface Bar {
    foo: Foo
}
interface Baz {
    bar: Bar
}

let a: Partial<Baz> = {}

//... Goal:
a.bar.foo.data = 'newData'

This action is not permitted due to potentially undefined properties. An unwieldy solution is as follows:

a = {
    ...a,
    bar: {
        ...a?.bar,
        foo: {
            ...a?.bar?.foo,
            data: 'newData'
        }
    }
} as Partial<Baz>

Is there a more graceful way to accomplish this task?

ts playground example

Answer №1

Utilize the nullish coallecesing assignment operator (??=) for accomplishing this task:

((a.bar ??= {}).foo ??= {}).data = 'newData';

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

Compel a customer to invoke a particular function

Is there a way to ensure that the build method is always called by the client at the end of the command chain? const foo = new Foo(); foo.bar().a() // I need to guarantee that the `build` method is invoked. Check out the following code snippet: interface ...

Is it normal for the Array of Observables to be empty upon initial page load, only to contain content later

Currently, I am working on integrating ngx-infinite-scroll functionality. My goal is to extract the initial 5 posts from my "posts" array and populate them into the "shownPosts" array at the beginning. Subsequently, as the user continues scrolling down, I ...

What is the process for sending an HTTP post request with a React/Typescript frontend and a C#/.Net backend?

In the frontend code, there is a user login form that accepts the strings email and password. Using MobX State Management in the userstore, there is an action triggered when the user clicks the login button to submit the strings via HTTP post. @action logi ...

Invoke a function within an Angular component that is passed in as a parameter

Is it possible to invoke a function using a string in JavaScript? I have a scenario where I receive a string as the function name, and I need to call and run that function. However, my current code is not working as expected. Below is the code snippet I ...

Visual Studio Code continues to compile code automatically without requiring me to save any changes

Question: VSC triggers compilation even without any file changes in Angular(6) project ng serve It's frustrating when Visual Studio Code starts compiling repeatedly, even when no changes have been made. How can I prevent this from happening? I&apos ...

iterating over a nested map within a map in an Angular application

I wrote a Java service that returns an observable map<k, map<k,v>> and I'm currently struggling to iterate through the outer map using foreach loop. [...] .then( (response: Package) => { response.activityMap.forEach((key: s ...

What are the best practices for handling dynamic content internationalization in Angular?

According to Angular.io, the i18n tag is used to mark translatable content. It should be placed on every element tag that requires translation of fixed text. Now, what if we have an element with dynamic content? For example, consider a table displaying a ...

The NestJS framework encountered an error due to a method being undefined in the

Encountering Error with NestJS Function create123: TypeError - Cannot read properties of undefined (reading 'create123') The constructor is displayed below \`export class AuthenticationService { constructor( private readonly usersServ ...

Adding an active class on a selected chat list item in Angular - here's how!

We are currently developing a chat component where users can click on the left side chat item to open messages with the selected user. We have implemented an active class that changes the color of the selected chat list item. Our goal is to apply the activ ...

Angular's HostListener triggers twice when the browser's back button is clicked

In my Angular application, I have implemented a @HostListener that triggers when the back button on the browser is clicked. However, I have noticed that the event handler seems to be firing twice - prompting two dialogue boxes when clicking 'Ok'. ...

Matching only the specified Records in an array of Typescript generic objects

Check out this demo: https://tsplay.dev/Nnavaw I am working with an array that has the following structure: Array<{ id?: string; text?: string; date?: Date; }> This conflicts with the current implementation: data: Array<Par ...

Receiving undefined when subscribing data to an observable in Angular

Currently, I am facing an issue in my Angular project where subscribing the data to an observable is returning undefined. I have a service method in place that retrieves data from an HTTP request. public fetchData(): Observable<Data[]> { const url = ...

Angular 4 animation issue: duration of transitions not being properly implemented

Why isn't the transition working as expected? Even though the animate function is set with a time of 2 seconds, the transition happens instantly. trigger('showMenu', [ state('active', style({ marginLeft: '0px' }) ...

A comprehensive guide to using Reactive Forms in Angular

I need help understanding how FormGroup, FormControl, FormArray work in Angular. The error message I'm encountering is: Type '{ question: FormControl; multi: true; choices: FormArray; }' is not assignable to type 'AbstractControl' ...

Leveraging Promise in conjunction with async/await

As I venture into the world of async/await in TypeScript, I find myself pondering a few questions. Specifically, I have been working on a function to extract an ArrayBuffer from a Blob. async function readAsArrayBuffer(blob: Blob): Promise<ArrayBuffer& ...

Converting a string URL to an object type in TypeScript

Is there a way to convert a string URL into an object type in TypeScript? Here is some sample code: type KeyUrl<T> = T extends `/${infer U}` ? U : never; type TUrl<T> = { [k in KeyUrl<T>]: string }; // ---------------------------------- ...

Retrieve the data from the mat-checkbox

My goal is to retrieve a value from a mat-checkbox, but the issue is that we only get boolean expression instead of the string value. Here's an example snippet of what I'm looking for: <mat-checkbox formControlName="cb2" <strong&g ...

When working with React and Typescript, I encountered an issue with refs causing a typescript error: "The property 'current' does not exist on the type '(instance: HTMLInputElement | null) => void'"

I am working on a component that requires a ref prop: import React, {forwardRef, ReactElement, ReactNode, HTMLProps, useRef} from 'react' import styles from './index.module.css' import classNames from 'classnames' import { Ico ...

Redis Recursion: The callstack has reached its maximum size limit

Looking for some assistance with creating a game timer. I've decided to utilize Redis and Web Sockets in order to synchronize the timer across multiple devices. However, I'm running into an issue when trying to call my function recursively using ...

TypeScript Error 2304: Element 'div' is nowhere to be found - CRA TypeScript Template

I'm experiencing a problem in VSCode while working on the default create-react-app my-app --template typescript project. It seems to not recognize any HTML elements, as I keep getting the error cannot find name xxx, where 'xxx' represents th ...