Goal
Install the TypeScript compiler, write a first .ts file, and see how tsc type-checks and emits JavaScript.
1. Install TypeScript
npm install -g typescript
Prefer a project-local install? Use npx tsc after npm install -D typescript.
Check the version:
tsc -v
2. Your first program
Create an empty folder and a file hello.ts:
// Greets the world.
console.log("Hello world!");
This looks like JavaScript : because TypeScript is JavaScript with optional types. Run:
tsc hello.ts
No type errors means little console output. Look in the folder: you now have hello.js next to hello.ts. That is the compiled (emitted) JavaScript.
// Greets the world.
console.log("Hello world!");
3. Catch an error with tsc
Rewrite hello.ts:
function greet(person, date) {
console.log(`Hello ${person}, today is ${date}!`);
}
greet("Brendan");
Run tsc hello.ts again:
Expected 2 arguments, but got 1.
You still wrote plain-looking JavaScript, and TypeScript found a real bug: a missing argument.
4. Emitting with errors
Open hello.js after that failed check : TypeScript still emitted JavaScript by default. That is intentional: when you migrate existing JS, you may want to run code while you fix types.
To stop emit when there are errors:
tsc --noEmitOnError hello.ts
hello.js will not update until the errors are gone.
5. Optional: a small project config
For real work, use a tsconfig.json so you are not passing flags every time:
tsc --init
A solid starting point for new projects:
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"strict": true,
"noEmitOnError": true,
"outDir": "dist",
"rootDir": "src"
},
"include": ["src"]
}
Then put sources in src/ and run tsc with no file arguments : it reads the config.
Try it
- Create
greet.tswith a two-parametergreetfunction. - Call it with one argument and run
tsc. - Fix the call, then run with
--noEmitOnErrorand confirmgreet.jsupdates only when clean.