codez.guru

Installing TypeScript

To use TypeScript, install it as a dev dependency in your project:

npm install typescript --save-dev

Or install globally:

npm install -g typescript

Then confirm it’s installed:

tsc --version

Creating a tsconfig.json File

Run the following command to generate a base config:

npx tsc --init

This creates a tsconfig.json file which controls how TypeScript compiles your code.


Basic Compiler Options

Here’s a minimal tsconfig.json for most projects:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "outDir": "dist",
    "rootDir": "src",
    "strict": true,
    "esModuleInterop": true
  },
  "include": ["src"]
}
Option Purpose
strict Enables all type-checking rules
esModuleInterop Allows import x from 'y' style imports
rootDir/outDir Control where your source and compiled files live

Compiling TypeScript to JavaScript

Place your .ts files in a src/ folder, then run:

npx tsc

This compiles .ts files into .js in the dist/ folder (or wherever you configured).


Working with TypeScript in Node.js

Add this to package.json:

"scripts": {
  "build": "tsc",
  "start": "node dist/index.js"
}

Use ts-node for quicker development:

npm install ts-node --save-dev

Run a file:

npx ts-node src/index.ts

Summary

  • Install TypeScript via npm
  • Generate a tsconfig.json to control compilation
  • Use tsc or ts-node to compile/run code
  • Setup proper src and dist folders for clean separation

Next up: basic types and how to annotate your variables like a pro.