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