TypeScript Tutorial menu

TypeScript Get Started

To use TypeScript on your computer you need Node.js and the TypeScript compiler, called tsc.

Step 1: Install Node.js

Download Node.js (the LTS version) from its official website and install it. It comes with npm, the Node package manager. Check that both work in a terminal (Command Prompt, PowerShell or Terminal):

Example

bash
node -v
npm -v
Output
v22.11.0
10.9.0

Your version numbers may be different. Any recent version is fine.

Step 2: Install TypeScript

Install TypeScript inside your project folder:

Example

bash
mkdir ts-practice
cd ts-practice
npm init -y
npm install --save-dev typescript
npx tsc -v
Output
Version 5.6.3

npx runs the tsc that is installed in your project.

Step 3: Write a TypeScript File

Create a file called hello.ts:

Example

typescript
const student: string = "Ali";
const marks: number = 88;

function report(name: string, score: number): string {
  return `${name} scored ${score} out of 100`;
}

console.log(report(student, marks));

Step 4: Compile and Run

Example

bash
npx tsc hello.ts
node hello.js
Output
Ali scored 88 out of 100

tsc checks the types and creates hello.js, a plain JavaScript file. Node.js then runs that file. If there is a type error, tsc prints it with the file name and line number.

What the Compiled File Looks Like

Open hello.js. The types are gone:

Example

javascript
const student = "Ali";
const marks = 88;
function report(name, score) {
    return `${name} scored ${score} out of 100`;
}
console.log(report(student, marks));

Step 5: Create tsconfig.json

Real projects have a tsconfig.json file with the compiler settings. Create one with:

Example

bash
npx tsc --init

A simple setup looks like this:

Example

json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "strict": true,
    "outDir": "dist",
    "rootDir": "src"
  }
}
OptionMeaning
targetWhich JavaScript version to output
moduleWhich module system to use for import and export
strictTurns on all the strict type checks (recommended)
outDirThe folder for the compiled .js files
rootDirThe folder with your .ts files

Now put your .ts files in src, and just run npx tsc to compile the whole project. Add --watch to recompile every time you save.

Use Visual Studio Code as your editor. It has TypeScript support built in, so errors are underlined as you type, before you even compile.

Exercise

Exercise

Which command compiles a file called app.ts into JavaScript?

Learn TypeScript with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp