How to make Typescript tsconfig strict

Nov 5, 2022 - 2 min read

How to make Typescript tsconfig strict

Hello my dear friend! Hope you are doing well in those turbulent times. I am writing this post to share my experience with building enterprise React Typescript projects and how to manage them gracefully.

The problem

Typescript has a miryad of settings in tsconfig.json, and apart from the most obvious that you should always do ("strict": true), take a look at the list of the most interesting ones:

"allowUnreachableCode": true, "allowUnusedLabels": true, "exactOptionalPropertyTypes": true, "noFallthroughCasesInSwitch": true, "noImplicitOverride": true, "noImplicitReturns": true, "noPropertyAccessFromIndexSignature": true, "noUncheckedIndexedAccess": true, "noUnusedLocals": true, "noUnusedParameters": true

I have found noUncheckedIndexedAccess to be particularly effective, because by default every index from an array is seen as the array element type. Even if it exceeds the items available and will result in undefined

Enabling “noUncheckedIndexedAccess” requires you to check the element before using it.

For example, assume there is a black magic website that sells gifts on holidays:

export type ExtraGift = { name: string; price: number; }; export const getExtraGift = (name: string): ExtraGift => { const extraGift = extraGifts[name] ?? [name, price: 0]; return extraGift; }

The Solution

Anyhow, this is what I would consider a "decent" tsconfig starter to get "production-ready" React Typescript project around, and if you want, you can play with some extra settings from the list at the top

// tsconfig.json { "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "noUncheckedIndexedAccess": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx" }, "include": ["src"], "exclude": ["node_modules"], "extends": "./tsconfig.paths.json" } // tsconfig.paths.json { "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["src/*"] } } }

What is the number one lesson you have learned from this article?