'Typescript: why spread is not safe?

This is is very irretating and often case in typescript, why spread operator not safe:

type M = {
  a: string;
  b: string;
}

declare const m: M

const m2: M = {
  ...m, 
  ...{x : 1} // this thing can be anything, without error
}

Can anyone explain what prevents TS from considering this an error?



Solution 1:[1]

Quoting the documentation about TypeScript being a structurally typed language:

let o = { x: "hi", extra: 1 }; // ok
let o2: { x: string } = o; // ok

Here, the object literal { x: "hi", extra: 1 } has a matching literal type { x: string, extra: number }. That type is assignable to { x: string } since it has all the required properties and those properties have assignable types. The extra property doesn’t prevent assignment, it just makes it a subtype of { x: string }.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jsejcksn