1

The following code does not transpile, as I would expect.

interface Interface1 {
    a: number;
    b: number;
}

const arr: Array<Interface1> = []

arr.push({
    a: 1,
    b: 1,
    c: 1
})

However, as soon as I turn the pushed object into an interface (not matching interface 1), the code successfully transpiles.

interface Interface2 {
    a: number;
    b: number;
    c: number;
}

const test: Interface2 = {
    a: 1,
    b: 1,
    c: 1
}

arr.push(test)

What is going on, and how can I successfully throw a typeError upon this incorrect array push?

Reproduction link: https://codesandbox.io/s/flamboyant-knuth-8lq82?file=/src/index.ts

Cyon
  • 414
  • 1
  • 4
  • 13
  • 2
    This is called [excess property checks](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks) and it works exactly this way. "Fresh" object literals are checked for extra properties. "Non-fresh" object literals (ones that have been assigned to variables) are not. – jcalz Aug 28 '20 at 21:03
  • 1
    Possible duplicate of [Is there an alternative to Partial to accept only fields from another type and nothing else?](https://stackoverflow.com/questions/56606614/is-there-an-alternative-to-partial-to-accept-only-fields-from-another-type-and-n) – jcalz Aug 28 '20 at 21:06

0 Answers0