Start using TypeScript
Write and compile your first program
Create a TypeScript file, catch one mistake, and inspect the JavaScript produced by the compiler.
Let’s write some TypeScript and watch the compiler do its two jobs: check the code, then turn it into JavaScript.
In the project folder, create index.ts:
const greeting: string = 'Hello'
console.log(greeting.toUpperCase())
The : string part is a type annotation. It tells TypeScript what kind of value greeting holds.
Compile it, then run the JavaScript it produced:
npx tsc index.ts
node index.js
You should see HELLO printed. Notice the two steps. tsc reads the .ts file and writes a .js file next to it. node runs the .js file. Node.js never sees your TypeScript.
Open index.js and look at what came out:
var greeting = 'Hello';
console.log(greeting.toUpperCase());
The : string is gone. That is the compiler removing the types. You may also notice const became var and semicolons appeared. Without a configuration file, tsc targets a very old version of JavaScript by default. We fix that when we create a tsconfig.json later in the course.
Catch your first error
Now introduce a mistake on purpose:
const greeting: string = 42
console.log(greeting.toUpperCase())
Compile again. TypeScript refuses the number:
index.ts(1,7): error TS2322: Type 'number' is not assignable to type 'string'.
Read the parts. The file, the line and column, an error code, and a plain message. You promised greeting would be a string, then gave it a number. The compiler spotted the contradiction before the program ran.
Errors do not always block output
Here is a detail that surprises people. Look in the folder after that failed compile. index.js is still there, and it was rewritten:
var greeting = 42;
console.log(greeting.toUpperCase());
Run it with node index.js and you get the crash TypeScript warned you about:
TypeError: greeting.toUpperCase is not a function
By default, TypeScript emits JavaScript even when it finds errors. This is deliberate. It lets you run code you are in the middle of migrating. But it also means a build script that only runs tsc can ship broken output. Later we will use noEmitOnError, or a separate --noEmit check, when a workflow must stop on errors.
One more thing. You did not have to annotate anything. Delete : string from the working version and compile again. It still checks, because TypeScript can see that 'Hello' is a string. That is inference, and we look at it properly in the next module.
Try this on your own: restore the string, add const length = greeting.length, and hover over length in your editor. TypeScript infers number without another annotation.
Lesson completed