Eliminating Dead Code in TS Projects
Real-world projects inevitably accumulate dead code. It bloats the bundle a bit, but the bigger pain is chasing down why a change “doesn’t work” only to realize the code never runs. My rule of thumb: delete it all. If someone says, “What if we need it someday?” my answer is, “What day exactly? We have Git history for that—don’t hide behind laziness or lack of professionalism. Delete it.”
Teams have different experience levels and perspectives. Instead of repeatedly cleaning up after others, enforce rules—and maybe share an article like this one to back up the rationale.
Alright, let’s dive in.
Built-in TSConfig options
The TypeScript compiler ships with two flags that help cut down dead code.
"compilerOptions":{
"noUnusedLocals": true,
"noUnusedParameters": true,
}
noUnusedLocals
Unused local variables trigger an error, as shown below:
noUnusedParameters
Unused function parameters trigger an error as well:
How to avoid the errors
Sometimes you genuinely need a placeholder parameter, such as in callbacks where the index of each argument matters. In that case, prefix the unused parameter with an underscore. The TypeScript compiler ignores those, and naming them with numbers helps clarify their position.
TS rules
tslint-no-commented-code-rule
Some folks comment out code with promises to clean it later—rarely happens. This rule flags commented code longer than two lines.
Configuration
yarn add tslint-no-commented-code-rule -D
tslint.json
"no-commented-code": [ true, { "minLineCount": 2, "ignoredCommentRegex": "^(\\w+$|TODO|FIXME)" } ]
no-unused-variable
This rule is no longer recommended.
ts-unused-exports
With the compiler settings and lint rules above, a lot of cruft disappears. One gap remains: unused exports (functions, classes, constants).
Lint rules work on a single file at a time, so they can’t detect unused exports. You’d want support at the TypeScript compiler level, but it’s not there yet. See the discussions:
- https://github.com/microsoft/TypeScript/issues/13408
- https://github.com/microsoft/TypeScript/issues/29293
I considered building something until I found an existing tool: ts-unused-exports.
Configuration
- yarn add -D ts-unused-exports
- ts-unused-exports ./tsconfig.json –showLineNumber –ignoreTestFiles
Wire it into your hooks—pre-commit
, for example—to keep dead code from ever landing.
Final Thoughts
- These settings keep most redundancy out of the codebase. Rules help, but leveling up the team matters even more.
- Clean code is an ongoing pursuit—this is just one small step. Keep spotting and fixing issues.