Setting Up TypeScript
Setting Up TypeScript
Section titled “Setting Up TypeScript”Installation
Section titled “Installation”TypeScript can be installed globally or as a project dependency.
# Install globally (not recommended for projects)npm install -g typescript
# Install as a project dependency (recommended)npm install --save-dev typescript
# Verify the installationnpx tsc --version# Output: Version 5.x.xRecommendation: Always install TypeScript as a
devDependencyper project. This ensures every developer uses the same version.
Project Initialization
Section titled “Project Initialization”Create a tsconfig.json file to configure the TypeScript compiler:
# Generate a default tsconfig.jsonnpx tsc --initThis creates a tsconfig.json with sensible defaults. For a new project, start with this configuration:
{ "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "outDir": "./dist", "rootDir": "./src" }, "include": ["src/**/*.ts"], "exclude": ["node_modules", "dist"]}tsconfig.json Deep Dive
Section titled “tsconfig.json Deep Dive”Every option in tsconfig.json controls how TypeScript behaves:
Core Options
Section titled “Core Options”| Option | Purpose | Recommended |
|---|---|---|
target | Which JS version to compile to | ES2022 or ESNext |
module | Module system for output | ESNext, CommonJS, or NodeNext |
strict | Enable all strict type checks | true |
outDir | Output directory for compiled JS | ./dist |
rootDir | Source directory | ./src |
Strict Mode Flags
Section titled “Strict Mode Flags”When strict: true is enabled, these individual checks are turned on:
| Flag | What It Does |
|---|---|
noImplicitAny | Error when TypeScript can’t infer a type |
strictNullChecks | null and undefined are only assignable to unknown, any, and their respective types |
strictFunctionTypes | Enables stricter checking of function types |
strictBindCallApply | Checks arguments to bind, call, apply |
strictPropertyInitialization | Class properties must be initialized in constructor |
noImplicitThis | Error when this has an implicit any type |
alwaysStrict | Always emit "use strict" |
Project Structure
Section titled “Project Structure”A typical TypeScript project structure:
my-project/├── src/│ ├── index.ts # Entry point│ ├── types/│ │ └── index.ts # Shared type definitions│ ├── utils/│ │ ├── helpers.ts│ │ └── validation.ts│ └── services/│ └── api.ts├── dist/ # Compiled output (gitignored)├── tests/│ └── index.test.ts├── tsconfig.json├── package.json└── .gitignoreCompiling TypeScript
Section titled “Compiling TypeScript”# Compile oncenpx tsc
# Compile in watch mode (recompiles on changes)npx tsc --watch
# Check types without emitting filesnpx tsc --noEmit
# Compile a single filenpx tsc src/index.ts --outDir dist
# Compile with a specific config filenpx tsc --project tsconfig.jsonBuild Scripts in package.json
Section titled “Build Scripts in package.json”{ "scripts": { "build": "tsc", "watch": "tsc --watch", "typecheck": "tsc --noEmit", "clean": "rm -rf dist" }}ESLint + TypeScript
Section titled “ESLint + TypeScript”npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin{ "parser": "@typescript-eslint/parser", "plugins": ["@typescript-eslint"], "extends": [ "eslint:recommended", "plugin:@typescript-eslint/recommended" ], "rules": { "@typescript-eslint/no-explicit-any": "warn", "@typescript-eslint/explicit-function-return-type": "off" }}Project Architecture: TypeScript Compilation
Section titled “Project Architecture: TypeScript Compilation”flowchart LR TSSRC[.ts Source Files<br/>src/] --> TSC[TypeScript Compiler<br/>tsc --noEmit] TSSRC --> BUILD[Build Tool<br/>tsc / esbuild / vite] TSC -->|Type Check ✅| CLEAN[Type-safe Code] BUILD --> JS[.js Output<br/>dist/] JS --> DEPLOY[Deploy to<br/>Browser / Node]
TSCONFIG[tsconfig.json<br/>Configures everything] -.-> TSC TSCONFIG -.-> BUILD
style TSSRC fill:#7c3aed,color:#fff style TSC fill:#3b82f6,color:#fff style BUILD fill:#f59e0b,color:#fff style JS fill:#059669,color:#fff style TSCONFIG fill:#ec4899,color:#fff style DEPLOY fill:#10b981,color:#fffFlow: Write
.tsinsrc/→tscchecks types (in CI:--noEmit) → build tool emits.jstodist/→ deploy. Thetsconfig.jsonfile is the control panel that tells everything how to behave.
TypeScript with Bundlers
Section titled “TypeScript with Bundlers”Vite:
npm create vite@latest my-app -- --template react-tsWebpack:
npm install --save-dev ts-loadermodule.exports = { entry: './src/index.ts', module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ } ] }, resolve: { extensions: ['.tsx', '.ts', '.js'] }};VS Code Integration
Section titled “VS Code Integration”VS Code has built-in TypeScript support. Key features:
| Feature | Shortcut |
|---|---|
| Go to Definition | F12 |
| Find References | Shift + F12 |
| Rename Symbol | F2 |
| Quick Fix | Ctrl + . |
| Type Hints | Hover over variable |
| Auto Import | Type and select from suggestions |
Enable these in settings.json:
{ "typescript.updateImportsOnFileMove.enabled": "always", "typescript.suggest.autoImports": true, "typescript.preferences.importModuleSpecifier": "relative"}Common Mistakes
Section titled “Common Mistakes”| Mistake | Fix |
|---|---|
| Installing TypeScript globally | Use npm install --save-dev typescript per project |
Not using strict: true | Enables critical type safety checks |
Ignoring tsconfig.json errors | Fix configuration before coding |
| Mixing module systems | Match module to your bundler’s requirements |
Best Practices
Section titled “Best Practices”- Always use
strict: truein tsconfig.json - Add
build,watch, andtypecheckscripts to package.json - Run
tsc --noEmitin CI to prevent type errors from reaching production - Keep
rootDirandoutDirseparate so compiled JS doesn’t pollute source - Use
.gitignoreto excludedist/andnode_modules/
Interview Questions
Section titled “Interview Questions”Easy: How do you create a new TypeScript project from scratch?
Medium: What does strict: true enable in tsconfig.json?
Hard: Explain the difference between target, module, and moduleResolution in tsconfig.json and when you’d use each.