Installing TypeScript and First Program

Install

You need Node.js (LTS) installed. Then install the TypeScript compiler tsc in your project:

Example

mkdir hello-ts && cd hello-ts
npm init -y
npm install --save-dev typescript
npx tsc --version

Example output

Version 5.9.3

Tip: Install TypeScript per project (--save-dev) instead of globally, so every developer and the CI server use the same version.

Create tsconfig.json

Example

tsc --init creates a tsconfig.json with recommended settings. A small one looks like this:

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "commonjs",
    "strict": true,
    "outDir": "dist",
    "rootDir": "src"
  }
}

Write and Compile

Create src/index.ts:

const message: string = "Hello from TypeScript!";
console.log(message);

Example

Compile with tsc, then run the JavaScript with Node:

npx tsc
node dist/index.js

Example output

Hello from TypeScript!

Run TypeScript Directly: tsx and ts-node

During development you can skip the separate compile step:

Example

npm install --save-dev tsx
npx tsx src/index.ts

# older alternative
npx ts-node src/index.ts

# Node.js 22.6+ can strip simple types itself
node --experimental-strip-types src/index.ts

Example output

Hello from TypeScript!
ToolType-checks?Use for
tscyesbuilding for production, CI checks
tsxno (only strips types, very fast)running scripts and dev servers
ts-nodeyes by default (slower)older projects

Note: tsx does not check types. Run npx tsc --noEmit to check types without creating files.

Practice

Exercise: Write a program with a city variable of type string and a pincode variable of type number and print them on one line.

Show answer
const city: string = "Hyderabad";
const pincode: number = 500081;
console.log(city, pincode);