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
node -v
npm -vv22.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
mkdir ts-practice
cd ts-practice
npm init -y
npm install --save-dev typescript
npx tsc -vVersion 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
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
npx tsc hello.ts
node hello.jsAli 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
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
npx tsc --initA simple setup looks like this:
Example
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"outDir": "dist",
"rootDir": "src"
}
}| Option | Meaning |
|---|---|
target | Which JavaScript version to output |
module | Which module system to use for import and export |
strict | Turns on all the strict type checks (recommended) |
outDir | The folder for the compiled .js files |
rootDir | The 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?
