function foo<T extends object>(t: T): T { return { ...t // Error: [ts] Spread types may only be created from object types. } }
I am aware that there are issues on github, but I can't figure out what is fixed and what is not and they have 2695 open issues. So I am posting here. I am using latest Typescript 2.9.2.
Should the above code not work? And how can I fix it if possible?
If we are using TypeScript version 4 or beyond, we can spread tuple generic parameter types. This is useful to help TypeScript better infer types on expressions that involve tuples.
TypeScript Basics. The spread operator is a new addition to the features available in the JavaScript ES6 version. The spread operator is used to expand or spread an iterable or an array.
This is fixed in TypeScript Version 3.2. See Release Notes.
Looks like spread with a generic type isn't supported yet, but there is a GitHub issue about it: Microsoft/TypeScript#10727.
For now you can either use type assertion like @Jevgeni commented:
function foo<T extends object>(t: T): T { return { ...(t as object) } as T; }
or you can use Object.assign
which has proper type definitions.
function foo<T extends object>(t: T): T { return Object.assign({}, t); }
You can use Record<string, unknown>
or an interface like the below examples:
goodsArray.map(good => { return { id: good.payload.doc.id, ...(good.payload.doc.data() as Record<string, unknown>) }; });
or
goodsArray.map(good => { return { id: good.payload.doc.id, ...good.payload.doc.data() as Goods // 'Goods' is my interface name }; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With