Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Spread types may only be created from object types

Tags:

typescript

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?

like image 690
Morten Poulsen Avatar asked Jul 05 '18 10:07

Morten Poulsen


People also ask

Can you spread types in TypeScript?

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.

What is spread operator in TypeScript?

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.


2 Answers

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); } 
like image 54
jmattheis Avatar answered Oct 07 '22 08:10

jmattheis


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   }; }); 
like image 30
Muhammad Mabrouk Avatar answered Oct 07 '22 08:10

Muhammad Mabrouk