To fix the ‘TypeScript: Spread types may only be created from object types’ error, we can cast our variable into an object.
For instance, we write
const foo = <T extends object>(t: T): T => {
return { ...(t as object) } as T;
};
to cast t into an object with as so that the TypeScript compiler knows that t is an object.
Then we can use the spread operator on t without TypeScript compiler errors.
Conclusion
To fix the ‘TypeScript: Spread types may only be created from object types’ error, we can cast our variable into an object.