Start using TypeScript

Write and compile your first program

Create a TypeScript file, catch one mistake, and inspect the JavaScript produced by the compiler.

Time to write some TypeScript and watch the compiler do its two jobs: check your code, then turn it into JavaScript.

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 and run the emitted JavaScript:

npx tsc index.ts
node index.js

You should see HELLO printed. Notice the two-step flow: tsc reads the .ts file, node runs the .js file. Node.js never sees your TypeScript.

The compiler checks index.ts, removes the type annotation, and writes JavaScript. Open index.js and confirm that : string is gone. The emitted file is ordinary JavaScript, almost identical to what you wrote.

Catch your first error

Now introduce a mistake:

const greeting: string = 42

Run the compiler again. TypeScript reports that number is not assignable to string:

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-language message. You declared greeting as a string, then gave it a number, and the compiler caught the contradiction before the program ran.

Errors do not always block output

Here is a detail that surprises people. Check the directory after that failed compile: index.js was still written.

Depending on compiler settings, TypeScript can still emit JavaScript when errors exist. A type error is not automatically a runtime barrier. This is deliberate — it lets you run partially migrated code — but it 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 everything. Delete : string from the working version and compile again. It still checks correctly, because TypeScript can infer the type from the value 'Hello'. We explore inference properly in the next lessons.

Exercise: restore the string, add const length = greeting.length, and hover over length in your editor. TypeScript should infer number without another annotation.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →