20

I'm destructuring the result of a regex match

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

As the comment points out, fullMatch is never used and TSC wants me to know. Is there any way to suppress this error without turning off unused checks across the board?

I've also tried unpacking the array as an object:

const {
    1: stuffIWant, // Unexpected SyntaxError: Unexpected token :
} = str.match(/1(.*)2/);
Sandy Gifford
  • 7,219
  • 3
  • 35
  • 65

2 Answers2

33

Found an answer almost immediately (ain't it always the way) - when destructuring arrays you can ignore select values by adding an extra comma in:

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

    return stuffIWant;
}

getStuffIWant("abc1def2ghi");

No variable declared, nothing for TypeScript to get all up in arms about.

Sandy Gifford
  • 7,219
  • 3
  • 35
  • 65
1

Alternative syntax as of 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

Note: str.match can also return null, so the example in the question has an additional compilation error due to ts(2461)

kpowz
  • 429
  • 4
  • 6
  • This works for TS warnings, but my IDE still complains about it separately, seems like it may not be consistently applicable. – bsplosion Mar 08 '23 at 22:20