When I look at the signature of Object.assign I see that it uses intersection types, but the behavior is not what I expected.
I want to use Object.assign to merge some changes with an old object to create a new object (as is common practice in JS when following immutable data patterns) and have TypeScript validate that the parts and the result are correct, but it seems TypeScript allows anything through without an error.
For example:
interface Thing {
name: string;
age: number;
fav: boolean;
}
let oldThing: Thing = {
name: "Aaa",
age: 123,
fav: false
};
let newThing: Thing = Object.assign({}, oldThing, {
name: "Bbb",
age: "abc", // should be type error
fake: "fakey" // should be unknown prop error
});
Why does Object.assign allow this incorrect assignment to Thing? Is there a way to make this work close to what I expected?
Thingshould be a compile error on those properties. Maybe I don't understand how the type checker validates assignment.Object.assign. I'm kind of confused as to why there's so little information about this issue. I think it should be described in official docs.