TypeScript 解构对象数组,包括第一个对象和其中的值

TypeScript destructure array of objects, both first object and a value within it

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

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

在 Javascript 这行得通;但是在 TypeScript 中这个 returns

Cannot find name 'firstObjectInArray'.ts(2304)

我正在想办法输入它以避免错误。

由于 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 }