TypeScript - Spread types may only be created from object types

Viewed 846

Code below throws Spread types may only be created from object types:

const bool = true

console.log({ ...(bool || { foo: 'bar' }) })

While the following works fine, what caused the above error and how to suppress it?

const bool = true

console.log({ ...(bool && { foo: 'bar' }) })
2 Answers

When you do the ||, it evaluates the item on the left and tries to spread it. But it cannot spread a boolean variable, it can only spread an object.

When you do the &&, the expression in parens returns the { foo: 'bar' } object, which is spreadable.

To play with this, try:

console.log(true && 'hi') // "hi"
console.log(true || 'hi') // true

The first one translate like this

If bool is true or the object... In that case it's trying to spread the bool but seeing that bool is a Boolean not an object... You get the error

The second translate like this

If bool is true, then spread this object... The ampersand in that case is doing a check, making sure bool is true before spreading the object... This is equivalent to writing an if statement...

if (bool) console.log({ ...{ foo: 'bar' } })

Related