Setup and first program¶
This lesson gets TypeScript running on your machine and explains what happens when a .ts file becomes JavaScript.
What is TypeScript?¶
TypeScript is a typed layer on top of JavaScript. You write .ts files, the TypeScript compiler checks types, then emits plain JavaScript that runs in browsers, Node.js, or any JavaScript engine.
The types disappear at runtime. They exist to catch mistakes before the program runs.
Install the compiler¶
Use the compiler that ships with the typescript package.
Check the install:
Tip
A global install is fine for learning. Real projects usually install TypeScript as a dev dependency (npm install -D typescript) so every teammate uses the same version.
Your first file¶
Create hello.ts:
Compile and run it:
tsc hello.ts produces hello.js:
Notice the : string type annotation is gone. It only helped the compiler.
Create a project¶
A real project uses a tsconfig.json file so the compiler knows the rules.
tsconfig.json will contain many default settings. For learning, this minimal version is enough:
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "node",
"strict": true,
"outDir": "./dist",
"rootDir": "./src",
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*"]
}
| Setting | Purpose |
|---|---|
target |
JavaScript language version to emit |
module |
Module system for imports/exports |
strict |
Enables stronger type checking |
outDir |
Where compiled JavaScript goes |
rootDir |
Where source TypeScript lives |
Create src/index.ts:
Compile:
Run the emitted file:
Watch mode¶
For fast feedback while learning, run the compiler in watch mode. It recompiles whenever you save.
Tip
Keep one terminal running npx tsc --watch and another running node dist/index.js when you try the hands-on tasks.
Hands-on: temperature converter¶
- Create a project with
tsconfig.jsonpointingrootDiratsrcandoutDiratdist. - Add
src/temperature.ts. - Write a function
celsiusToFahrenheit(c: number): numberthat returns(c * 9/5) + 32. - Call it with a few temperatures and
console.logthe results. - Compile with
npx tscand runnode dist/temperature.js. - Introduce an error on purpose: pass a string to
celsiusToFahrenheitand see the compiler error.
What did the error teach you?
TypeScript noticed the wrong argument type before the program ran. Remove the wrong call and recompile.
Try it in the playground¶
function celsiusToFahrenheit(c: number): number {
return (c * 9 / 5) + 32
console.log(celsiusToFahrenheit(25))
Common first mistakes¶
- Forgetting that
.tsfiles compile to.jsand then runningnode file.ts. Run the.jsoutput instead. - Writing
tscwithout atsconfig.jsonand getting unexpected output. Use--initor a project file. - Ignoring red squiggles. TypeScript warnings usually prevent real bugs.