Disable TypeScript 'declared but never read' check
By Flavio Copes
Fix the TypeScript error 'declared but its value is never read' by setting noUnusedLocals to false in tsconfig.json, plus noUnusedParameters for parameters.
To disable the '<variable>' is declared but its value is never read error, open your tsconfig.json file and set the noUnusedLocals compiler option to false:
{
"compilerOptions": {
"noUnusedLocals": false
}
}
Once you do, restart yarn start (or whatever runs your dev server) to pick up the new setting.
Why does this error happen?
TypeScript raises this error (its code is TS6133) when the noUnusedLocals option is enabled and you declare a variable you never use:
const total = 145 //'total' is declared but its value is never read.
The check exists to catch dead code. An unused variable is often a leftover from a refactoring, or a sign you forgot to finish something.
The error will not go away until you use that variable somewhere, or you turn the check off.
Silencing a single line
If this happens on one line only, you can add // @ts-ignore on the line before the problematic one, and TypeScript will skip it.
This gets old fast though. In my case the error would pop up again immediately on the next line, so a per-line comment was useless. That’s when changing tsconfig.json makes sense.
Unused function parameters
There’s a separate option for unused function parameters, called noUnusedParameters. You can set it to false in the same way.
But for parameters there’s a nicer trick: prefix the parameter name with an underscore, and TypeScript stops complaining about that one parameter:
button.addEventListener('click', (_event) => {
console.log('clicked')
})
This is handy when a callback receives arguments you don’t need, but you can’t remove them because they come before one you do need.
Note that the underscore trick only works for parameters. A local variable named _total still triggers the noUnusedLocals error.
Re-enable the checks later
One thing I recommend: disable these checks while you’re in “building mode”, when code changes fast and half-written functions are normal.
But re-enable them as soon as your code starts to finalize. A build that fails on unused variables is annoying while prototyping, and precious right before shipping, because those variables are almost always something you meant to delete or forgot to wire up.
Related posts about typescript: