Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript assignment chaining

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?

like image 455
xiaoxiyao Avatar asked Jan 30 '26 00:01

xiaoxiyao


2 Answers

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

like image 124
Nullndr Avatar answered Feb 01 '26 12:02

Nullndr


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

like image 29
Mina Avatar answered Feb 01 '26 14:02

Mina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!