【问题标题】:TypeScript destructure array of objects, both first object and a value within itTypeScript 解构对象数组,包括第一个对象和其中的值
【发布时间】:2020-12-18 10:04:46
【问题描述】:

我有一个要解构的对象数组,检索第一个对象和其中的一个值:

const [{ a }] = ([firstObjectInArray] = [
  {
    a: 1,
  },
  {
    b: 2,
  },
]);
console.log(a); // 1
console.log(firstObjectInArray); // { a: 1 }

在 Javascript 中这是有效的;但在 TypeScript 中返回

Cannot find name 'firstObjectInArray'.ts(2304)

我正在尝试弄清楚如何输入它以避免错误。

【问题讨论】:

  • 请看你之前的问题。
  • 为什么不按照previous question: const [first] = [{ a: 1 }], { a } = first 中提到的那样进行两次单独的解构。
  • 请重新阅读我对上一个问题的评论
  • 在当前问题中,使用const [first] = someArray, { a } = first有什么问题?
  • 此问题中提供的示例适用于 Javascript;我想知道 TypeScript 错误来自哪里。

标签: javascript typescript destructuring


【解决方案1】:

由于firstObjectInArray 不是您的声明的一部分(它只是一个表达式),它是对未声明变量的赋值。

要解决这个问题,你有两种方法:

  • 分两步完成:

    const [firstObjectInArray] = [
        {
          a: 1,
        },
        {
          b: 2,
        },
      ];
    const {a} = firstObjectInArray
    console.log(a); // 1
    console.log(firstObjectInArray); // { a: 1 }
  • 提前声明firstObjectInArray

    let firstObjectInArray; //<-- This can't be made `const`, as it has no initializer
    const [{ a }] = ([firstObjectInArray] = [
      {
        a: 1,
      },
      {
        b: 2,
      },
    ]);
    console.log(a); // 1
    console.log(firstObjectInArray); // { a: 1 }

【讨论】:

  • 不喜欢这些解决方案,但解释了问题。谢谢。
  • 第一个正确的解决方案(并且优于第二个)。你甚至可以在一个声明中做到这一点:const [firstObjectInArray] = …, {a} = firstObjectInArray;.
  • @Bergi 你能详细说明一下吗?
  • @Bergi 我认为你错了,这是不可能的。
  • @EmilleC。 “不可能”是什么意思?
【解决方案2】:

你可以用这种方式解构一个对象数组:

const [firstObjectInArray, ...rem] = [{ a: 1 }, { b: 2 }];

并以这种方式访问​​值:

console.log(firstObjectInArray); // {a: 1}

const { a } = firstObjectInArray;
console.log(a); // 1

【讨论】:

    猜你喜欢
    • 2020-03-22
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    相关资源
    最近更新 更多