【问题标题】:Type of a rest array in a destructured object解构对象中剩余数组的类型
【发布时间】:2018-09-30 13:24:52
【问题描述】:

如何在此处将c 注释为任意类型的可选数组?

const a = ({ b, ...c }: { b: string, c: ? }) => null

【问题讨论】:

  • 当你说“可选”时,你是什么意思? c 永远是一个对象。它可能是空的(如果调用 a 时使用的对象除了 b 之外没有其他属性),但它始终是一个对象。
  • 没错,我的意思是空的。

标签: typescript flowtype


【解决方案1】:

由于这是属性解构,它不会是数组,而是object

const a = ({ b, ...c }: { b: string, c: object}) => null;

实时非 TypeScript 示例:

const a = ({ b, ...c }) => {
  console.log("typeof c:", typeof c);                 // true
  console.log("Array.isArray(c):", Array.isArray(c)); // false
  console.log(JSON.stringify(c));                     // '{"x":1,"y":2,"z":3}'
};
a({x: 1, y: 2, z: 3});

【讨论】:

    【解决方案2】:

    如您所述,任意类型的可选数组:c?: Array<any>

    const a = ({b, c}: { b: string, c?: Array<any> }): void => null
    

    例子:

    const a = ({b, c}: { b: string, c?: Array<any> }): void => {
      console.log('b:', b)
      if (c instanceof Array) {
        for (let item of c) {
          console.log('c item:', item)
        }
      }
    }
    
    a({b: '1', c: [1]})
    a({b: '1'})  
    

    {b, c}: 正在解包,bc 都是变量。 {b, ...c}: 是非法声明。 .

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-02
      • 1970-01-01
      • 1970-01-01
      • 2017-02-02
      • 2022-01-03
      • 2023-03-04
      • 2022-10-13
      相关资源
      最近更新 更多