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
What happend when use assignment chaining? How to resolve this type error?
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
What happend when use assignment chaining? How to resolve this type error?
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
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 = '';
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 = {};