Suppress unused variable error for destructured arrays Suppress unused variable error for destructured arrays typescript typescript

Suppress unused variable error for destructured arrays


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.


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)