Typescript: Do not report excess property errors on spread

Created on 6 Nov 2017  路  8Comments  路  Source: microsoft/TypeScript

The result of a spread operator should not contribute to the excess property checks. only the properties listed in the object literal should be checked. i.e.:

declare var x: { a: number };

var y: { b: number } = { ...x, b: 0 };  // no errors on x, but should be OK
var z: { b: number } = { ...x, b: 0, c: 1 };  // c is excess
Bug Fixed

Most helpful comment

Why is this a bug? I'm using this to get excess property checking to work when assigning an object of one type to another.

cause the error here is not correct really. types are open in TS, so you can easily defeat the check here, and you do not get the error elsewhere either.. e.g.

const x = { a: 0 , b: 0 } ;
const y : { a: number } = x; // no error
const z: { a : number } = { ...x } // error.. why?

All 8 comments

Why is this a bug? I'm using this to get excess property checking to work when assigning an object of one type to another.

const a: TypeA;
const b: TypeB = a; // does not do EPC
const b: TypeB = {...a}; // does EPC

Are there any other workarounds to get EPC when you aren't using object literals?

Why is this a bug? I'm using this to get excess property checking to work when assigning an object of one type to another.

cause the error here is not correct really. types are open in TS, so you can easily defeat the check here, and you do not get the error elsewhere either.. e.g.

const x = { a: 0 , b: 0 } ;
const y : { a: number } = x; // no error
const z: { a : number } = { ...x } // error.. why?

Makes sense that this inconsistency should be fixed. Is there any workaround to force excess property checking in the case when you do want it?

Is there any workaround to force excess property checking in the case when you do want it?

This is tracked by https://github.com/Microsoft/TypeScript/issues/12936

We're running into this issue. I'm confused by your original comment though.

// no errors on x, but should be OK

Did you mean it does error on x?

the contents of x are not checked for excess properties...

@mhegazy I have a question/concern about this. If using the spread operator is not going to report excessive property checks, this makes the new object dangerous do use.

For example, you can have a const newObject: NewType = { ...oldObject } and later, for instance, POST this parameter to a service, thinking you are only sending over NewType properties, but in fact you are also sending over some other properties that you are not aware of.

@ktalebian this behavior is not unique to the spread operator. If you changed your example to just const newObject: NewType = oldObject it would work the same way.

As mentioned above, types are open in TypeScript. This is a design decision. But there鈥檚 a proposal (#12936) for the behavior you鈥檙e looking for.

Was this page helpful?
0 / 5 - 0 ratings