抑制解构数组的未使用变量错误

Suppress unused variable error for destructured arrays

我正在解构正则表达式匹配的结果

function getStuffIWant(str: string): string {
    const [
        fullMatch,   // [ts] 'fullMatch' is declared but its value is never read.
        stuffIWant,
    ] = str.match(/1(.*)2/);

    return stuffIWant;
}

getStuffIWant("abc1def2ghi");

正如评论所指出的,fullMatch 从未使用过,TSC 希望我知道。 有没有办法在不全面关闭未使用的检查的情况下抑制此错误?

我也试过将数组解包为一个对象:

const {
    1: stuffIWant, // Unexpected SyntaxError: Unexpected token :
} = str.match(/1(.*)2/);

几乎立即找到答案(不是总是这样)- 在解构数组时,您可以 ignore select values 通过在

中添加一个额外的逗号
function getStuffIWant(str: string): string {
    const [
        , // full match
        stuffIWant,
    ] = str.match(/1(.*)2/);

    return stuffIWant;
}

getStuffIWant("abc1def2ghi");

没有声明变量,TypeScript 没有什么可以全力以赴的。

TypeScript 4.2 的替代语法:

function getStuffIWant(str: string): string {
  const [
      _fullMatch,
      stuffIWant,
  ] = str.match(/1(.*)2/);

  return stuffIWant;
}

getStuffIWant("abc1def2ghi");

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-2.html#destructured-variables-can-be-explicitly-marked-as-unused

注意str.match也可以returnnull,所以题中的例子由于ts( 2461)