Typescript: Spread operator + unknown key doesn't result in a type error

Created on 17 Mar 2017  路  4Comments  路  Source: microsoft/TypeScript



TypeScript Version:

TypeScript 2.2.1

Code

interface TestProps {
  foo: string;
  bar: string;
}

function test(mode: number, vars: TestProps): TestProps {
  switch (mode) {
    case 1:
      return { 
        foo: 'a',
        bar: 'b',
        other: 'c', // This is an error
      };
    case 2:
      return {
        ...vars,
        other: 'c', // This SHOULD be an error
      }
  }

  return {
    foo: 'a',
    bar: 'b',
  }
}

Expected behavior:

The spread operator with an unknown attribute should show a type error.

Actual behavior:

The spread operator with an unknown attribute does not show a type error.

Duplicate

Most helpful comment

This is a pretty big issue I've run into while using Redux, where all state changes require copying the object keys and overwriting a subset, just like case 2. I've had to make a special function that wraps Object.assign but catches unknown props.

All 4 comments

This is a pretty big issue I've run into while using Redux, where all state changes require copying the object keys and overwriting a subset, just like case 2. I've had to make a special function that wraps Object.assign but catches unknown props.

Duplicate of https://github.com/Microsoft/TypeScript/issues/13878, this is behaving as design, the excess property checks are disabled for spread. you can read more about this in https://github.com/Microsoft/TypeScript/issues/12997

I read through both tickets and don't really understand why they are disabled. Could you please clarify?

@mhegazy @brandonwamboldt I just put a few thoughts on #12997 . I hope this decision gets reconsidered. Thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MartynasZilinskas picture MartynasZilinskas  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments

jbondc picture jbondc  路  3Comments

zhuravlikjb picture zhuravlikjb  路  3Comments

blendsdk picture blendsdk  路  3Comments