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

Sometimes, we want to fix the ‘TypeScript: Spread types may only be created from object types’ error.

In this article, we’ll look at how to fix the ‘TypeScript: Spread types may only be created from object types’ error.

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

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.

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.