抑制无序数组的未使用变量错误

时间:2018-11-21 21:11:00

标签: typescript destructuring

我正在破坏正则表达式匹配的结果

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/);

2 个答案:

答案 0 :(得分:1)

几乎立即找到了答案(并非总是如此)-解构数组时,您可以ignore select values,方法是在其中添加一个额外的逗号:

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

    return stuffIWant;
}

getStuffIWant("abc1def2ghi");

没有声明任何变量,TypeScript也无济于事。

答案 1 :(得分:0)

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 也可以返回 null,所以问题中的例子由于 ts(2461) 有一个额外的编译错误

相关问题