TypeScript - Spread 类型只能从对象类型创建

TypeScript - Spread types may only be created from object types

下面的代码抛出 Spread types may only be created from object types:

const bool = true

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

虽然以下工作正常,但导致上述错误的原因是什么以及如何抑制它?

const bool = true

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

当您执行 || 时,它会评估左侧的项目并尝试传播它。但是它不能传播一个布尔变量,它只能传播一个对象。

当你执行 && 时,括号中的表达式 returns { foo: 'bar' } 对象,它是可扩展的。

要玩这个,试试:

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

第一个这样翻译

如果 bool 为真或对象...在那种情况下它试图传播 bool 但发现 bool 是一个布尔值而不是对象...您得到错误

第二次这样翻译

如果 bool 为真,则传播此对象...在这种情况下,& 符号正在执行检查,确保在传播对象之前 bool 为真...这相当于编写一个 if 语句...

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