diff --git a/README.md b/README.md index 8d15ed2..432e6f9 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/typescript/compiler-checks-for-unused-params-and-variables.md b/typescript/compiler-checks-for-unused-params-and-variables.md new file mode 100644 index 0000000..afe19b6 --- /dev/null +++ b/typescript/compiler-checks-for-unused-params-and-variables.md @@ -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, + } +} +```