1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Compiler Checks For Unused Params And Variables as a typescript til

This commit is contained in:
jbranchaud
2021-03-29 13:47:43 -05:00
parent 58b0fe0716
commit 9ad1dee0f0
2 changed files with 47 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
_1102 TILs and counting..._
_1103 TILs and counting..._
---
@@ -1002,6 +1002,7 @@ _1102 TILs and counting..._
### TypeScript
- [Add Types To An Object Destructuring](typescript/add-types-to-an-object-destructuring.md)
- [Compiler Checks For Unused Params And Variables](typescript/compiler-checks-for-unused-params-and-variables.md)
- [Re-Export An Imported Type](typescript/re-export-an-imported-type.md)
- [Zero-Config Environments For Trying Out Types](typescript/zero-config-environments-for-trying-out-types.md)

View File

@@ -0,0 +1,45 @@
# Compiler Checks For Unused Params And Variables
There are a number of linter-esque checks that you can tell the TypeScript
compiler to make when it is checking your code. There are two that prevent
values from going unused: one for parameters and the other for variables.
The [`noUnusedLocals`](https://www.typescriptlang.org/tsconfig#noUnusedLocals)
config, which defaults to `false`, can be set to `true`. This will cause the
compiler to fail if a locally declared variable goes unused.
```typescript
function printItem(item: any, index: number) {
const indexedItem = `${index}: ${item}`;
// ^^^ 'indexedItem' is declared but its value is never read.
console.log(item);
}
```
The
[`noUnusedParameters`](https://www.typescriptlang.org/tsconfig#noUnusedParameters)
config, which also defaults to `false`, can be set to `true`. This will cause
the compiler to fail if a function param goes unused.
Fixing the previous error could then result in this one.
```typescript
function printItem(item: any, index: number) {
// ^^^
// 'index' is declared but its value is never read.
console.log(item);
}
```
Here is what the `tsconfig.json` would look like:
```json
{
"compilerOptions": {
"noUnusedLocals": true,
"noUnusedParameters": true,
}
}
```