I have a playground for this question here.
In the following code, typescript does error on the assignment to t2_2 ("not assignable") but not on t2_1, where I have the "x" property in some other variable, which I spread into the assignment.
Why does it not complain about the assignment to t2_1?
type Type1 {
a: number;
b: number;
}
type Type2 = {
t1: Type1
s: string;
}
let t1: Type1 = {a:1,b:2}
let tx = {x:2};
let t2_1: Type2 = {
t1,
s: "asdf",
...tx
}
let t2_2: Type2 = {
t1,
s: "asdf",
x: 3
}
When you spread in
tx, you don't know what properties it really has. So TypeScript doesn't really know if you have excess properties in some cases.However,
xvery explicitly appears to be an excess property. It is statically known to be there - TS can always tell.See