Categories
TypeScript Answers

How to fix the ‘TypeScript: Spread types may only be created from object types’ error?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *