JavaScript and TypeScript course ยท Module 6: TypeScript Basics
TypeScript configuration and tools
In this lesson7
In Jurassic Park, even the best genetic system is useless without proper calibration of the laboratory equipment. Similarly, TypeScript without proper configuration won't reach its full potential. The tsconfig.json file is your control panel - it defines how the TypeScript compiler interprets and transforms your code.
tsconfig.json - command center
Every TypeScript project starts with a tsconfig.json file in the root directory. This is a JSON file defining compiler options, which files should be compiled, and how the output should look:
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}Key compiler options
Target - output JavaScript version:
ES5- compatibility with older browsersES2020- modern environments (nullish coalescing, optional chaining)ESNext- latest features
Module - module system:
CommonJS- Node.js (require/module.exports)ESNext- ES modules (import/export)NodeNext- Node.js with ESM support
Lib - which APIs are available:
DOM- browser API (document, window)ES2020- methods likePromise.allSettled,BigIntWebWorker- Web Workers API
Strict Mode - maximum safety
The strict: true flag enables all rigorous checks at once. It's like turning on full security in Jurassic Park - no dinosaur will escape the enclosure:
// strict: true enables ALL of the following:
{
"strictNullChecks": true, // null/undefined must be handled
"strictFunctionTypes": true, // strict typing of function parameters
"strictBindCallApply": true, // strict typing of bind/call/apply
"strictPropertyInitialization": true, // properties must be initialized
"noImplicitAny": true, // implicit any is forbidden
"noImplicitThis": true, // this must have a type
"alwaysStrict": true, // "use strict" in every file
"useUnknownInCatchVariables": true // catch(e) is unknown, not any
}Example difference with strictNullChecks:
// WITHOUT strictNullChecks - runtime error!
function getDinoName(id: string): string {
const dino = dinosaurs.find(d => d.id === id);
return dino.name; // Runtime error: Cannot read property 'name' of undefined
}
// WITH strictNullChecks - TypeScript enforces null handling
function getDinoName(id: string): string | undefined {
const dino = dinosaurs.find(d => d.id === id);
return dino?.name; // Safe - returns undefined if not found
}Path Aliases - navigation shortcuts
In large projects, imports can become unreadable. Path aliases allow you to create shortcuts:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@models/*": ["src/models/*"],
"@utils/*": ["src/utils/*"],
"@services/*": ["src/services/*"],
"@config": ["src/config/index.ts"]
}
}
}Instead of:
import { Dinosaur } from '../../../models/dinosaur';
import { formatDate } from '../../utils/helpers';You write:
import { Dinosaur } from '@models/dinosaur';
import { formatDate } from '@utils/helpers';Declaration Files (.d.ts)
Declaration files describe types for JavaScript code. They have the .d.ts extension and contain no implementation - only type signatures:
// dinosaur.d.ts - type declaration
declare interface IDinosaur {
id: string;
name: string;
species: string;
dangerLevel: 1 | 2 | 3 | 4 | 5;
}
declare function findDinosaur(id: string): IDinosaur | null;
declare const PARK_NAME: string;
// Module declaration for a JS library without types
declare module 'dino-tracker' {
export function trackPosition(id: string): [number, number];
export function getStatus(id: string): 'active' | 'sleeping' | 'escaped';
}Three types of declaration files:
- Automatic - TypeScript generates them with the
declaration: trueflag - Manual - you write them yourself for JS code without types
- DefinitelyTyped - community types for popular libraries
DefinitelyTyped (@types/*)
Many JavaScript libraries don't have built-in types. The DefinitelyTyped repository contains community-created types:
# Installing types for popular libraries
npm install --save-dev @types/node
npm install --save-dev @types/express
npm install --save-dev @types/lodash
npm install --save-dev @types/jestTypeScript automatically recognizes @types/* packages - you don't need to import them. If a library has built-in types (like axios or date-fns), you don't need a separate @types package.
The typeRoots option in tsconfig controls where TypeScript loads types from:
{
"compilerOptions": {
"typeRoots": ["./node_modules/@types", "./src/types"]
}
}ESLint with TypeScript
TypeScript has its own type checks, but ESLint with the @typescript-eslint plugin adds stylistic rules and advanced analysis:
{
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking"
],
"parserOptions": {
"project": "./tsconfig.json"
},
"rules": {
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }],
"@typescript-eslint/prefer-nullish-coalescing": "error",
"@typescript-eslint/prefer-optional-chain": "error"
}
}Most important @typescript-eslint rules:
no-explicit-any- warns about usinganyno-unused-vars- detects unused variables (with TypeScript support)prefer-nullish-coalescing- prefer??instead of||prefer-optional-chain- prefera?.binstead ofa && a.bstrict-boolean-expressions- forbids implicit boolean conversions
Code quality options
Additional compiler flags to help maintain code quality:
{
"compilerOptions": {
"noUnusedLocals": true, // error on unused variables
"noUnusedParameters": true, // error on unused parameters
"noImplicitReturns": true, // every path must return a value
"noFallthroughCasesInSwitch": true, // enforces break in switch
"noUncheckedIndexedAccess": true, // arr[i] is T | undefined
"exactOptionalPropertyTypes": true // undefined !== omitting a field
}
}The noUncheckedIndexedAccess option is particularly useful - it protects against indexing errors:
const dinos = ["T-Rex", "Raptor", "Triceratops"];
// WITHOUT noUncheckedIndexedAccess
const first: string = dinos[0]; // OK, but dinos[100] would also be "string"!
// WITH noUncheckedIndexedAccess
const first: string | undefined = dinos[0]; // TypeScript enforces checking
if (first) {
console.log(first.toUpperCase()); // Safe
}Code for this lesson: index.ts
// TypeScript configuration - Jurassic Park Laboratory
// === 1. STRICT MODE IN ACTION ===
// strictNullChecks - forces you to handle null/undefined
interface IDinosaur {
id: string;
name: string;
species: string;
dangerLevel: 1 | 2 | 3 | 4 | 5;
}
const dinosaurs: IDinosaur[] = [
{ id: "001", name: "Rexy", species: "T-Rex", dangerLevel: 5 },
{ id: "002", name: "Blue", species: "Velociraptor", dangerLevel: 4 },
{ id: "003", name: "Bumpy", species: "Ankylosaurus", dangerLevel: 2 },
];
// Safe lookup that handles undefined
function findDino(id: string): IDinosaur | undefined {
return dinosaurs.find(d => d.id === id);
}
const dino = findDino("001");
if (dino) {
console.log("Found:", dino.name, "- danger level:", dino.dangerLevel);
} else {
console.log("Dinosaur not found");
}
// === 2. PATH ALIASES (simulation) ===
// In a real project:
// import { Dinosaur } from '@models/dinosaur';
// import { formatDate } from '@utils/helpers';
// Instead of: import { Dinosaur } from '../../../models/dinosaur';
// === 3. DECLARATION FILES (.d.ts) ===
// Simulated type declarations for a JS library
// This is what the dino-tracker.d.ts file would look like:
// declare module 'dino-tracker' {
// export function trackPosition(id: string): [number, number];
// export function getStatus(id: string): DinoStatus;
// }
// We use the types as if the library existed:
type DinoStatus = "active" | "sleeping" | "escaped";
function getStatus(id: string): DinoStatus {
const dino = findDino(id);
if (!dino) return "escaped";
return dino.dangerLevel >= 4 ? "active" : "sleeping";
}
console.log("Rexy's status:", getStatus("001"));
console.log("Blue's status:", getStatus("002"));
// === 4. noUncheckedIndexedAccess ===
const species = ["T-Rex", "Raptor", "Triceratops"];
// With noUncheckedIndexedAccess: species[0] is string | undefined
const first = species[0];
if (first !== undefined) {
console.log("First species:", first.toUpperCase());
}
// === 5. DEFINITELYTYPED ===
// Installing types:
// npm install --save-dev @types/node @types/express @types/lodash
// TypeScript recognizes them automatically
// === 6. ESLINT WITH TYPESCRIPT ===
// Examples of @typescript-eslint rules:
// prefer-nullish-coalescing: use ?? instead of ||
const parkName: string | null = null;
const displayName = parkName ?? "Jurassic Park"; // better than ||
console.log("Park:", displayName);
// prefer-optional-chain: use ?. instead of &&
interface ParkConfig {
security?: {
fences?: {
voltage?: number;
};
};
}
const config: ParkConfig = { security: { fences: { voltage: 10000 } } };
const voltage = config.security?.fences?.voltage; // better than config && config.security && ...
console.log("Fence voltage:", voltage, "V");
// noImplicitReturns: every path must return a value
function classifyThreat(level: number): string {
if (level >= 4) return "HIGH THREAT";
if (level >= 2) return "MEDIUM THREAT";
return "LOW THREAT"; // required by noImplicitReturns
}
console.log("Classification (5):", classifyThreat(5));
console.log("Classification (1):", classifyThreat(1));Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which of the following flags is NOT enabled by the "strict": true option in tsconfig.json?
2. What is the role of .d.ts files (declaration files) in TypeScript?
These are 2 of 4 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Fix strict mode issues: strictNullChecks, noUncheckedIndexedAccess, noImplicitReturns, and configure path aliases.
- Code editor
Write a SecurityEvent interface, implement checkPerimeter and logEvent, and create a DinoSize type with a classifyBySize function.
- Vertical ordering
Order tsconfig options from most important (enable first) to advanced:
- Click in order
Arrange the path alias configuration elements in tsconfig.json:
- Vertical ordering
Arrange the steps for creating a new TypeScript project:
Tasks after this lesson
- QuestionFlags Not Covered by strict
- QuestionDeclaration Files (.d.ts)
- Coding taskStrict Mode - Practice
- QuestionDefinitelyTyped (@types/*)
- Coding taskDeclaration Files - Practice
- Put in ordertsconfig Options - From Basic to Advanced
- Click in orderPath Alias Syntax in tsconfig
- Put in orderTypeScript Project Configuration
- QuestionThe never Type