Open
Description
TypeScript Version: 3.0.1
Search Terms:
spread index signature, spread indexer
Code
declare var v: Record<string, string>;
let v2 = {...v}; // works
let v3 = {a: '', ...v}; // index signature lost
let v4 = {...v, a: ''}; // same as above
let v5 = {a: 1, ...v}; // index signature lost, should be '{a: number, [x: string]: number | string}'
let v6 = {[Number()]: 1, ...v}; // empty object type ò,Ó, should be '{[x: string]: number | string}'
Expected behavior:
Index signature exists on all object types.
Actual behavior:
Index signature is lost if object literal contains another property assignment. I'm not entirely sure what the type of v6
should be.
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
RyanCavanaugh commentedon Oct 9, 2018
I think it's extremely arguable one way or the other. Certainly if you introduce a non-conforming property, the original intent of the index signature is lost.
don't drop index signatures when spreading object
Record<string, any>
gives wrong type #30538jsingerlenovo commentedon Mar 18, 2021
Object.assign is able to handle the types correctly, why can't Object Spread?
number
#43698joealden commentedon Jan 10, 2022
As mentioned above, the type inference of
Object.assign
currently differs from the type inference of the object spread syntax. While to my understanding their behaviors don't map 1:1, in this scenario, I would personally expect them to both result in the same types being inferred. I'm not advocating for which way to type them (although personally I think that the less restrictive option seems more intuitive), but I do think that it makes sense for these two "object merge" techniques to be consistent?Here's an newer playground link that shows that this behaviour still exists in TS 4.5:
https://www.typescriptlang.org/play?#code/MYewdgzgLgBA5gUygIQIYQQeQEYCsHCwC8MAFAJQBcMASgSAE4AmAPNAwJZhwA0M7XODAA+MAK5gmCAGZcETAHwwiSgN4AoGFpgMkYhmBiqYABwYgTCBlACeARmoAiRzAC+AbnUf160JFggeARQdsowOPiEAHToEBxwYKSIKOhYQYQUfMZmFla2AExOUAjQLq7knn4QIAA2CFE1IHCkgZEhUTmW1vYVPlUB6VD5YcZRY8loGBHBmabmXQVFJVBlleDVdQ1NLYP5HfN5PZ7qQA
bmillwood commentedon May 2, 2022
I was linked here from a StackOverflow question I asked, after noticing during code review a variable being assigned an incorrect type in a way that the compiler did not catch. My minimal reproduction:
Here
abr
contains both string and number values, despite the type saying it should only contain strings. It feels like in the presence of this bug I either need to manually type-check spread operators where I see them, or else avoid using them at all.21 remaining items