Introduction to TypeScript: The Typed JavaScript

6 min read

Welcome to the TypeScript course! 🚀

If JavaScript is the cool, chaotic friend who throws a party but forgets to tell you the address until you're already driving, TypeScript is the responsible friend who sends a calendar invite with a map, dress code, and dietary restriction survey three weeks in advance.

In this module, we are going to look at what TypeScript is, why the industry is obsessed with it, and how to get your machine ready to write some type-safe code.


1. The "Why" Before the "How": Why TypeScript?

The Problem: The JavaScript Wild West 🤠

JavaScript is a dynamically typed language. This means variables do not have a fixed type. You can assign a number to a variable, and then five lines later, assign a function to that same variable.

While this offers flexibility, it creates a massive problem: Runtime Errors.

Imagine you are building a banking app.

  1. You have a function calculateTotal(price, tax).
  2. You expect numbers.
  3. Someone accidentally passes a string "100" as the price.
  4. JavaScript says, "Sure, whatever!" and returns "10020" (concatenation) instead of 120 (math).
  5. You don't find out until the user screams that their bank balance looks wrong.

This is the "undefined is not a function" nightmare that keeps developers up at night.

The Solution: Static Typing with TypeScript 🛡️

Definition: TypeScript is a superset of JavaScript. This means it is JavaScript, but with an added layer of features—specifically, static typing.

TypeScript allows you to define the shape of your data before you run the code. If you try to pass a string where a number is expected, TypeScript will yell at you (throw an error) before you even save the file.

Industry Fact: A study found that TypeScript could have prevented 15% of public bugs in JavaScript projects on GitHub. That sounds small until you realize 15% of your time is roughly 6 hours a week saved from debugging.

Real-life Scenario:

  • JavaScript: Building a Lego set where all the pieces are just in a giant pile. You might force a square block into a round hole. It fits if you push hard enough, but the structure collapses later.
  • TypeScript: The Lego manual. It tells you exactly which piece fits where. If you grab a square block for a round hole, the manual says, "No, stop that."

2. Setting up the Environment: Node, tsc, and tsconfig

To write TypeScript, we need to install the tools that translate it into code the computer understands.

Step 1: Install Node.js

TypeScript requires Node.js to run the compiler.

  • Check if you have it: Open your terminal and run node -v.
  • If not: Download the LTS version from the official Node.js website.

Step 2: Initialize a Project

We will follow industry standards here. We avoid installing things "globally" on your computer because different projects might need different versions of TypeScript. We install it locally in the project.

  1. Create a folder for your project and open it in your terminal.
  2. Initialize a standard Node project:
    bash
    npm init -y
    (This creates a package.json file, which tracks your project's dependencies.)

Step 3: Install the TypeScript Compiler (tsc)

Run the following command to install TypeScript as a "dev dependency" (meaning we only need it while coding, not when the app runs for the user):

bash
npm install typescript --save-dev

Step 4: The Configuration File (tsconfig.json)

You can tell TypeScript how strict you want it to be. We need a configuration file.

Run this command:

bash
npx tsc --init

(Note: We use npx to run the TypeScript compiler we just installed locally.)

This creates a tsconfig.json file. Open it up. You will see a lot of scary options commented out. Don't panic. Focus on these three for now:

  1. target: Likely set to es2016 or higher. This tells TS what version of JavaScript to output.
  2. module: Usually commonjs or esnext. This handles how files talk to each other.
  3. strict: Set to true. Crucial. This turns on the "strict mode" features that make TypeScript actually useful.

3. Your First TypeScript Program: "Hello World"

Let's write some code.

The File Extension

JavaScript files end in .js. TypeScript files end in .ts.

Action: Create a new file named index.ts.

Writing the Code

In index.ts, type the following:

typescript
let message: string = "Hello World";
console.log(message);

Analyzing the Syntax

Notice the : string part? This is a Type Annotation.

  • Definition: You are explicitly telling the compiler, "The variable message will always be a string."

The "Aha!" Moment 💡

Try to break it. Add this line below the previous code:

typescript
message = 10;

If you are using an editor like VS Code, you will see a red squiggly line under message. Hover over it. It will say:

Type 'number' is not assignable to type 'string'.

This is the magic. You caught a bug without running the code. In JavaScript, this would have run perfectly fine until it crashed your app logic later.


4. Understanding the Compilation Process: TS to JS

Here is a hard truth: Browsers (Chrome, Firefox) and Node.js generally do not understand TypeScript.

If you try to run node index.ts directly, it will fail (unless you use specific tools like ts-node, but natively, it fails).

The Concept: Transpilation

We need to translate our fancy TypeScript into plain, boring JavaScript that the browser understands. This process is called Transpilation (compiling source code to source code).

Under the Hood:
The TypeScript Compiler (tsc) strips away all the type definitions (: string, interface, etc.) and downgrades modern syntax if your tsconfig.json asks it to.

Hands-on: compiling the code

Go back to your terminal. Run:

bash
npx tsc
  1. Look at your file structure. You should now see a new file: index.js.

  2. Open index.js. It looks like this:

    javascript
    "use strict";
    let message = "Hello World";
    console.log(message);
    // Notice: The ': string' annotation is GONE.
  3. Now, run the JavaScript file:

    bash
    node index.js

    Output: Hello World

Summary of the Flow

  1. Write code in .ts files with types.
  2. Compile using tsc to check for errors.
  3. Generate clean .js files.
  4. Run the .js files in the browser or Node.

🧠 Quick Recap

  • JavaScript is risky because variables can change types unpredictably.
  • TypeScript enforces types statically (at compile time) to catch bugs early.
  • You install it via npm.
  • You write in .ts, but you actually run .js.

You have successfully set up your environment and written your first type-safe program. In the next section, we will dive into Basic Types and stop using strings for everything.


📚 References & Further Reading

Challenge

You have been given a piece of buggy code that calculates an order total. In its current state, it resembles plain JavaScript and is prone to runtime errors because it allows for mixing numbers and strings in calculations.

Your task is to leverage TypeScript to make the code type-safe and fix the existing errors.

  1. Add explicit type annotations to the calculateOrderTotal function parameters. productName must be a string, while quantity and unitPrice must be numbers.
  2. Add a return type annotation to the function, ensuring it explicitly declares that it returns a string.
  3. Examine the code that calls the function. Identify and correct all the lines that would cause a TypeScript compile-time error based on the type definitions you've just added.

Expected result

The corrected code should feature a fully typed function signature: function calculateOrderTotal(productName: string, quantity: number, unitPrice: number): string.

To fix the errors, the second function call should be corrected by changing the string argument "2" to a number 2.

Additionally, the final line that attempts to reassign order1_message must be corrected. Since order1_message is inferred to be a string from the function's return value, the numeric value 52.50 should be converted to a string, for example, "52.50" or String(52.50).

typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.