Description
Search Terms
- declared but never used noUnusedLocals
Suggestion
When you're destructuring an array, I want some variables/const to be declared but explicitly make them unused. Typescript has a feature of underscoring the unused parameters for functions:
const f = (a, _b) => a
But it doesn't work for array destruction:
const [a, _b] = [1, 2]
The motivation of the current behavior is that you can destruct array like this:
const [, , , d] = [1, 2, 3, 4]
But you can't do this (this is invalid syntax):
const f = (, , , d) => d
But whatever syntax is valid, what I say is that the ability to explicitly say a variable is unused, with leading underscore - it's good practice, it's convenient, and it should be supported when destructuring arrays, not in functions only.
P.S. Originally I've described the issue here - #31357, but it's wrongly described as a "bug request", so here's a feature request
Use Cases
Today you make some changes to the code that don't require such a variable, so you don't construct it from the array. You had a perfectly named variable, but you remove it. Tomorrow's programmer needs that variable, but he gives it a different name. Of course, there's code review, etc., so eventually it will get a proper name again - it just adds additional communication which is not needed, consumes time which could be used to something more useful.
Additionally, this syntax looks very weird (don't you think?):
const [, , , d] = [1, 2, 3, 4]
Instead, it's much better to have this:
const [_a, _b, _c, d] = [1, 2, 3, 4]
Examples
Having this code:
const [a, _b] = [1, 2]
const [_a, b] = [1, 2]
export { a, b }
To receive no errors from typescript when noUnusedLocals
is set to true.
- Here's a typescript playground
- A gist for that:
git clone git@gist.github.com:b08abed91888a739e4c9be6640f6b625.git test-ts-unused cd test-ts-unused tsc
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.