3
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?

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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 = {};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.