【问题标题】:TypeScript - Spread types may only be created from object typesTypeScript - 传播类型只能从对象类型创建
【发布时间】:2021-08-02 09:32:21
【问题描述】:

下面的代码抛出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' }) })

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

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

    当您执行&& 时,括号中的表达式返回{ foo: 'bar' } 对象,该对象是可展开的。

    要玩这个,请尝试:

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

    【讨论】:

    • 要传递这个错误,我们必须像console.log({ ...(<any>(bool || { foo: 'bar' })) })?还有其他方法吗?
    • 不,当布尔值传播时,这只会产生运行时错误。如果 bool 为真或假,你想发生什么?
    • 不,不会的,试一试。
    • 你是对的,它没有报错。但是味道不好闻!也许这读起来更好? console.log(bool ? { foo: 'bar' } : {})
    【解决方案2】:

    第一个这样翻译

    如果 bool 为真或对象...在这种情况下,它试图传播 bool 但看到 bool 是布尔值而不是对象...您会收到错误

    第二个这样翻译

    如果 bool 为真,则传播该对象...这种情况下的 & 符号正在做检查,确保 bool 为真,然后再传播该对象...这相当于编写一个 if 语句...

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

    【讨论】:

      猜你喜欢
      • 2018-07-21
      • 2019-09-10
      • 2018-12-13
      • 2020-08-02
      • 2020-05-26
      • 1970-01-01
      • 2020-02-07
      • 2021-12-31
      相关资源
      最近更新 更多