Home > Software design >  Typescript assignment chaining
Typescript assignment chaining

Time:12-06

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

Playground link

What happend when use assignment chaining? How to resolve this type error?

CodePudding user response:

Let's start with the first case:

let a: {
  m?: string
};

let b = a = {};

The type of b is inferred not from a, but from {}, this is why you can't access m from b.

In the second case

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

let b = a;

The type of b is inferred from a, that have the m property.

Why this?

Take the following example

let x = y = z;

y = z results in z, that's because the assignment is actually an expression.

So typescript check the type of z (in our case {}) and assign it to x (in our case b)

In order to fix the first case, you have to declare both a and b to { m?: string }.

type Foo = {
    m?: string;
}

let a: Foo;

let b: Foo = a = {}

Playground link

CodePudding user response:

With assignment chaining, the b variable gets the value of {} but does not get the type of a.

You need to create the type separately and apply it to b variable.

type A = {
    m?: string;
}

let a: A

let b: A = a = {};


b.m = '';

PLAYGROUND LINK

CodePudding user response:

Chaining the assignment operator is possible in order to assign a single value to multiple variables (link). So, assignment let b = a = {}; is the same as the sequence of commands let b = {}; a = {}, in this case, you can see that a never assigns to b, You can use the code below to get the expected result:

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