Chaining Assignments in TypeScript

let a: {
    m?: string
};

let b = a = {};

b.m = ''; // Property 'm' does not exist on type '{}'.


let a: {
    m?: string
} = {};

let b = a;

b.m = ''; // It's OK

Link to TypeScript Playground

What occurs when using assignment chaining? How can this type error be resolved?

Answer №1

Let's dive into the initial scenario:

let a: {
  m?: string
};

let b = a = {};

The type of b is actually inferred from {}, not from a. Hence, accessing m from b is not possible.

Now, let's consider the second situation:

let a: {
    m?: string
} = {};

let b = a;

In this case, the type of b is inferred from a, which contains the m property.

Why does this happen?

Consider this example:

let x = y = z;

The result is z because the assignment functions as an expression.

TypeScript determines the type of z (in our case {}) and assigns it to x (or b in our context)

To resolve the issue in the first case, both a and b need to be declared as { m?: string }.

type Foo = {
    m?: string;
}

let a: Foo;

let b: Foo = a = {}

Check out the playground here

Answer №2

When using assignment chaining, the variable b is assigned the value of {}, but it does not inherit the type of a.

To properly assign the type to variable b, you need to create a separate type and apply it.

type A = {
    m?: string;
}

let a: A;

let b: A = a = {};

b.m = '';

Check out this example in the Typescript Playground

Answer №3

One way to assign the same value to multiple variables is by chaining the assignment operator (link). For example, using let b = a = {}; is equivalent to let b = {}; a = {};. It's important to note that in this scenario, a gets assigned first before b. To achieve the desired outcome, you can utilize the following code snippet:

    let a: {
      m?: string
    };
    let b = a;
    b = a = {};

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

Issues with passing information from a child component to a parent component in a

Currently, I am developing a guessing game that involves questions and selection logic embedded in a component known as Questions. However, I am facing issues with App not being able to read the Questions code correctly. My objective is to have the state i ...

The difference between importing CSS in JavaScript and importing it directly in CSS lies in the way

Hello there, I am just starting out with web development and learning about Vue.js. In Vue 3, the recommended way to import CSS files from different packages is as follows: Method 1: Import directly in app.js //app.js import '../css/app.css'; i ...

Converting long date format to short date format: yyyy-mm-dd

Is there a way to convert the long date format from "Sat Dec 13 2014 06:00:00 GMT+0600" to "2014-12-13" in yyyy-mm-dd format? <script> function myDate(val) { var now = new Date("<?php echo $Cnextdue;?>"); now.setDate(now.getDate() + 30*val); ...

Synchronizing code paths that involve both ajax and non-ajax functions can be achieved by

My website features a basket functionality where users can enter an author's name and see the available books. After selecting desired books, they have the option to click on another author for more selection. The displayed list includes books by Step ...

Error in public build of Gatsby & Contentful site due to incorrect file paths

Encountering difficulties while attempting to deploy a Gatsby site with Contentful CMS. Development mode runs smoothly, but issues arise during the build process. Upon executing the Gatsby build command, the site is deployed successfully initially. Howeve ...

Having trouble with jQuery UI draggable when using jQueryUI version 1.12.1?

Currently, I am diving into the world of jQuery UI. However, I am facing an issue with dragging the boxes that I have created using a combination of HTML and CSS. My setup includes HTML5 and CSS3 alongside jQuery version 1.12.1. Any suggestions or help wou ...

Encountering Build Issue: "NgSemanticModule is not recognized as an NgModule" persists despite inclusion of dependencies and importing into primary module

I have posted my module, component, and package file here. I am attempting to implement a click event with ngif, but I keep encountering an error. The specific error message is "ERROR in NgSemanticModule is not an NgModule". I'm unsure if this error ...

JavaScript is claiming that my class method is invalid, despite the fact that it is obviously a valid function

Implementing a genetic algorithm using node has been my latest challenge. After browsing through the existing questions on this topic, I couldn't find anything relevant to my issue. The problem arises when I attempt to call the determine_fitness metho ...

How to use multiple template urls in Angular 6

Currently, I am creating a front-end using Angular 6 and facing the challenge of having components with varying html structures based on the user who is logged in. The number of templates required can range from 2 to over 20, so my preference would be to ...

Updating NPM yields no changes

Having trouble updating dependencies in a subfolder of my MERN stack app. Specifically, I am trying to update the dependencies in the client folder where the React code is located. However, when I attempt to update the dependencies in the client folder, it ...

The retrieval of JSON data in a JavaScript function is malfunctioning

I am new to working with Ajax and have reached the point where I am able to retrieve data. However, I am struggling to return the data as I keep getting undefined values. Below is the code snippet: function select_aragement(arragament){ var arrst = ar ...

Different ways to analyze elements from 2 arrays to hone in on specific values

I'm really struggling to solve this issue. I have two arrays - one for cars and the other for active filters. The cars array consists of HTML li tags with attributes like car type, number of seats, price, etc. On the other hand, the active_filters arr ...

Substitute this.bindMethod for function component

I have a class component that is structured like this: interface MyProps { addingCoord: any resetCoords: any } interface MyState { x: any y: any } class DrawerOld extends React.Component<MyProps, MyState> { width: number height: number ...

Having trouble extracting the ID from the URL using parameters

Just diving into the world of Express JS and MongoDB, so I appreciate your patience with me. Currently following a web development tutorial by Colt Steele. Take a look at my code: app.get("/:id",async(req,res)=> { const id= req.params[&apo ...

The Observable<T> generic type must be provided with one type argument

I encountered the following 3 errors while working with the Angular 2 (TypeScript) code below. Can you provide suggestions on how to resolve them? import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { NgModule, Com ...

Enable jquery offsetParent() function

$(document).ready(function(){ $("button").click(function(){ if ($("p").offsetParent().css("background-color") === "red") { $("p").offsetParent().css("background-color", "yellow"); } else { $("p").offsetParent().c ...

Incorporate a unique identifier for dynamic elements

Is there a way to give generated divs the same name so I can markup them easily? $.getJSON("data/reviews.json", function(data){ for(var i=0; i<data.length; i++) { var review = sym.createChildSymbol("Template", "content"); review.$("title").html ...

Maximizing the potential of $urlRouterProvider.otherwise in angular js

I am encountering an issue with redirecting to the login screen when there is no UABGlobalAdminId in my storage. I have tried using $urlRouterProvider.otherwise but it doesn't seem to be functioning properly. When I attempt to debug, the console does ...

Updating parent components through child components in ReactWould you like another unique

In my current project, I am attempting to change the state of the main component labeled App.tsx by using a child component called RemarksView.tsx. I have attempted passing props such as setRemarks and remarks, but unfortunately the state in the parent c ...

Executing a function by click event using the onclick attribute from a file located in the public directory of my project (Next

I'm new to using Next.js and I have a question about how to utilize onclick to execute a function from an external file located in my public folder. Below is my index.js file: import Head from "next/head" import Script from "next/scrip ...