TypeScript tsconfig.json and Strict Mode Explained
Edited by Dev Kilaru, Senior Data Analyst. How we make our content
Introduction
The tsconfig.json file controls how the TypeScript compiler checks and outputs your code. The single most valuable setting is strict, which turns on a group of checks that catch common bugs. This tutorial explains the key options and what strict mode actually protects you from.
Prerequisites
- TypeScript installed in a project
- Experience compiling a .ts file
Step-by-Step Guide
Step 1: Read a basic tsconfig.json
compilerOptions configures the compiler and include lists which files to compile. The right module and moduleResolution values depend on your runtime and build tool; check your framework's recommended settings.
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"outDir": "dist"
},
"include": ["src"]
}Step 2: Turn on strict mode
Setting strict to true enables several checks together, including noImplicitAny and strictNullChecks. Start new projects with it on.
Step 3: Catch null and undefined mistakes
With strictNullChecks, you must handle values that might be null before using them.
function length(text: string | null): number {
// return text.length;
// Error: 'text' is possibly 'null'.
return text ? text.length : 0;
}Step 4: Avoid implicit any
With noImplicitAny, a parameter without a type is an error instead of silently becoming any.
// function double(x) { return x * 2; }
// Error: Parameter 'x' implicitly has an 'any' type.
function double(x: number): number {
return x * 2;
}Step 5: Prefer unknown over any
unknown accepts any value but forces you to check its type before using it, which keeps the safety net in place.
function parse(json: string): unknown {
return JSON.parse(json);
}
const data = parse('{"a":1}');
if (typeof data === "object" && data !== null) {
console.log("It is an object");
}FAQs
- Is strict mode hard to adopt in an existing project?
- It can surface many errors at once. Migrate gradually by enabling individual strict flags one at a time, fixing errors as you go, then switch on strict when they all pass.
- What is the difference between any and unknown?
- any disables type checking for a value. unknown accepts any value but requires you to narrow it before you can use it, so it is the safer choice.
Summary
Start every project with strict: true. It catches missing null checks and untyped parameters early, and the small effort pays off in fewer runtime errors.
Related tutorials
- Schedule and Debug Shell Scripts: cron, bash -x, and Portability
- Shell Scripting Project: A Backup Script with Rotation and a Log Report
- Writing Safe Bash Scripts: set -euo pipefail, getopts, and trap
- Shell Pipes, Redirection, grep, sed, and awk for Text Processing
- Bash Loops, Arrays, and Functions Explained
Comments
Log in or create a free account to join the discussion.