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?
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 = '';
PLAYGROUND LINK
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With