'Typescript: Spread types may only be created from object types

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?



Solution 1:[1]

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
  };
});

Solution 2:[2]

Version 3.2 of Typescript fixed this. The two PRs that improve handling of spread and rest parameters are:

You can try it out now using npm install [email protected].

With 3.2 your code works as is.

Version 3.2 has been released on November 29th, 2018, you can read more about it here.

Solution 3:[3]

If you are still getting this error post version 3.2 then you probably have a type error 'upstream' resulting in an object being unknown instead of an actual object. For instance if you have the spread expression { ...getData() } but your getData function has a compile error you may see this error.

So check for any compiler errors in your browser console because the final error may be misleading.

Solution 4:[4]

This answer may help to fix the same problem while using angular and firestoe.

return { id: item.payload.doc.id, ...item.payload.doc.data()} as Employee

this on will throw he same error. for fixing you have to change like this one.

return { id: item.payload.doc.id, ...item.payload.doc.data() as Employee }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mikemaccana
Solution 2 stefanobaghino
Solution 3
Solution 4 Aathil Ahamed