TypeScript Introduction + Refactor

JavaScript... Lesson 5 of 5 25 min

TypeScript Introduction

Day 5: Level Up to TypeScript — Safer, Smarter JavaScript 🚀

Welcome to Day 5

You've spent four days writing JavaScript. You've built variables, functions, control flow, and a fully working DOM calculator. Now it's time to level up — to the language the professional web development world has largely moved to: TypeScript.

TypeScript is used by large companies like Microsoft, Airbnb, Slack, and Stripe. It powers modern frameworks like Next.js (React), NestJS, and Angular. In the blockchain world, tools like Hardhat and Ethers.js are written in TypeScript. If you're going to build serious web or Web3 applications, TypeScript is not optional — it's expected.

The great news: TypeScript isn't a completely new language. It's JavaScript with superpowers. Almost everything you already know still applies — you're just adding one powerful new concept on top: types.

Today's Goal: Understand why TypeScript exists, learn how to install and use it, master the core type system (string, number, boolean, interfaces, typed functions), and refactor your Day 4 calculator project from JavaScript into TypeScript — step by step.

Today's Roadmap

Part 1 — Understand TypeScript
What it is, why it exists, and how it compares to JavaScript
Part 2 — Install & Set Up
Install the TypeScript compiler globally with npm
Part 3 — Basic Types
Learn string, number, boolean, array, any, and union types
Part 4 — Type Annotations & Interfaces
Annotate variables and functions, define object shapes with interfaces
Part 5 — Refactor the Calculator
Convert your Day 4 project from JavaScript to TypeScript

What is TypeScript?

TypeScript is a programming language created by Microsoft in 2012. It is a superset of JavaScript — meaning every valid JavaScript file is also a valid TypeScript file. TypeScript adds one major feature on top of static typing.

But before we explain what that means, let's understand the problem TypeScript solves.

The Problem with Plain JavaScript

JavaScript is a dynamically typed language. This means variables don't have fixed types — they can hold any kind of data, and that data can change at any time. This is flexible, but it leads to bugs that are very hard to catch.

❌ JavaScript — Bug that's hard to notice:

//  no errors shown, but the result is wrong!
function add(a, b) {
    return a + b;
}

let result = add("10", 5);
// You expected: 15
// You got: "105"  ← Bug! String concatenation, not math!

// JavaScript did NOT warn you about this.
// You only find out when the app breaks for a user.

✅ TypeScript — Catches the bug immediately:

// TypeScript: specifies that a and b must be numbers
function add(a: number, b: number): number {
    return a + b;
}

let result = add("10", 5);
// TypeScript immediately shows an error in your editor:
// ❌ Argument of type 'string' is not assignable to parameter of type 'number'

// The bug is caught BEFORE you even run the code!

JavaScript vs TypeScript: When Do You Find the Bug?

🐛 JavaScript

1. Write the code ✓
2. Run the code ✓
3. User sees broken app ✗
4. Only NOW you find the bug

🛡 TypeScript

1. Write the code → Bug caught immediately! ✓
2. Fix it before running ✓
3. Run correct code ✓
4. User sees working app ✓

How TypeScript Works

Browsers don't understand TypeScript directly. They only understand JavaScript. So TypeScript must go through a compilation step — the TypeScript Compiler (tsc) reads your .ts files, checks for type errors, and outputs clean .js files the browser can run.

The TypeScript Workflow

📝 You Write
script.ts
TypeScript file
⚙️ Compiler
tsc
Checks types & compiles
❌ Type Error?
Stop!
Fix before continuing
OR
✅ Outputs
script.js
Clean JavaScript
🌐 Browser
Runs it
Normal JS execution

TypeScript in the Real World

Understanding where TypeScript is used helps you see why it matters:

🌐 Frontend Frameworks
Next.js (React), Angular, and Vue 3 all have first-class TypeScript support. Job listings for React developers almost always mention TypeScript.
⚙️ Backend Development
NestJS (the most popular Node.js enterprise framework) is written entirely in TypeScript. Express also has TypeScript type definitions.
⛓ Blockchain & Web3
Hardhat (the leading Ethereum development framework), Ethers.js, and The Graph all use TypeScript. Solidity smart contracts are often tested and deployed with TypeScript scripts.
🏢 Enterprise Software
Microsoft, Airbnb, Slack, Dropbox, Stripe, and thousands of other companies have migrated their codebases to TypeScript for reliability and maintainability.
The Bottom Line: JavaScript is the language of the browser. TypeScript is the language of professional developers who use JavaScript. Learning TypeScript now puts you ahead of most beginners and directly in line with how modern apps are built.

Installing TypeScript

TypeScript is installed using npm (Node Package Manager). You'll need Node.js installed on your computer first — if you've done any JavaScript development, you likely have it already.

Step 1: Check if Node.js is Installed

Open your terminal (Command Prompt on Windows, Terminal on Mac/Linux) and type:

node --version
npm --version

You should see version numbers like v18.17.0 and 9.6.7. If you see errors, download Node.js from nodejs.org first.

Step 2: Install TypeScript Globally

Run this command in your terminal:

npm install -g typescript

The -g flag means global — it installs TypeScript so you can use it from any folder on your computer.

This downloads the TypeScript compiler. It may take 30–60 seconds.

Step 3: Verify the Installation

tsc --version

You should see something like:

Version 5.3.3

Any version number means TypeScript is installed correctly. 🎉

Step 4: Your First TypeScript File

Create a folder called typescript-practice and inside it, create a file called hello.ts:

// hello.ts
let message: string = "Hello, TypeScript!";
console.log(message);

Now compile it in your terminal (make sure you're inside the folder):

tsc hello.ts

You'll notice a new file appeared: hello.js. Open it and you'll see:

// hello.js (generated by TypeScript compiler)
var message = "Hello, TypeScript!";
console.log(message);
Notice: TypeScript's type annotations (: string) are removed in the compiled JavaScript. Types only exist during development — they disappear at runtime. The browser never sees them.

Useful Compiler Flag: --watch Mode

Instead of typing tsc hello.ts every time you make a change, use watch mode — it automatically recompiles when you save your file:

tsc hello.ts --watch
# Now every time you save hello.ts, it auto-compiles to hello.js

Basic Types in TypeScript

TypeScript provides a set of built-in types that cover the most common kinds of data. You already know these concepts from Day 1 — TypeScript just makes them explicit and enforced.

1. string

The string type represents any text data.

// Annotating variables as string type
let firstName: string = "Alice";
let lastName: string = 'Wonderland';
let greeting: string = `Hello, ${firstName}!`;

// TypeScript prevents wrong assignment
firstName = "Bob";       // ✅ Fine — still a string
firstName = 42;          // ❌ Error: Type 'number' is not assignable to type 'string'
firstName = true;        // ❌ Error: Type 'boolean' is not assignable to type 'string'

Visual — Type protection in action:

firstName: string
accepts
"Alice" ✓
"Bob" ✓
"" ✓
rejects
42 ✗
true ✗
null ✗

2. number

The number type covers all numbers — integers, decimals, negative values.

let age: number = 25;
let price: number = 49.99;
let temperature: number = -5;
let percentage: number = 0.85;

// All valid number operations still work
let total: number = price * 1.08;
let nextAge: number = age + 1;

// TypeScript catches string being passed as number
let score: number = "100";  // ❌ Error! "100" is a string, not a number

3. boolean

The boolean type only accepts true or false.

let isLoggedIn: boolean = false;
let isStudent: boolean = true;
let hasPermission: boolean = false;

// From comparisons — these are automatically boolean
let isAdult: boolean = age >= 18;      // true
let isPassing: boolean = score > 60;  // depends on score

// Error cases
isLoggedIn = 1;       // ❌ Error: Type 'number' is not assignable to type 'boolean'
isLoggedIn = "true";  // ❌ Error: Type 'string' is not assignable to type 'boolean'

4. Array Types

Arrays in TypeScript are typed so every item in the array must be the same type.

// Two ways to write array types:
let scores: number[] = [85, 92, 78, 95];
let names: Array = ["Alice", "Bob", "Charlie"];

// Both are equivalent — use whichever feels natural
let flags: boolean[] = [true, false, true, true];

// TypeScript prevents mixing types in an array
scores.push(88);       // ✅ Fine — 88 is a number
scores.push("A+");    // ❌ Error: Argument of type 'string' is not assignable to parameter of type 'number'

5. any — The Escape Hatch (Use With Care)

Sometimes you genuinely don't know the type of something. TypeScript provides the any type, but it disables type checking — use it rarely.

// any turns off type checking — use only when necessary
let userInput: any = "hello";
userInput = 42;      // OK — no error (but no protection either)
userInput = true;    // Also OK — but TypeScript can't help you

// Better alternative: union types (either/or)
let flexible: string | number = "hello";
flexible = 42;       // ✅ OK — it's in the union
flexible = true;     // ❌ Error — boolean not in the union
Best Practice: Avoid any whenever possible. Using any is like turning TypeScript off — you lose all the safety benefits. A common saying among TypeScript developers: "If you're using any, you might as well use JavaScript."

Type Inference — TypeScript Is Smart

Here's something very useful: TypeScript can often figure out the type automatically from the value you assign. This is called type inference and it means you don't always need to write the type annotation explicitly.

// TypeScript infers the type from the value
let name = "Alice";     // TypeScript knows this is a string
let age = 25;           // TypeScript knows this is a number
let active = true;      // TypeScript knows this is a boolean

// It still protects you even without explicit annotation!
name = 42;              // ❌ Error: TypeScript inferred 'string', won't allow number
age = "old";            // ❌ Error: TypeScript inferred 'number', won't allow string
When to use explicit annotations:
• When declaring a variable without a value: let name: string;
• In function parameters (TypeScript can't infer these)
• When the inferred type is too broad and you want to be more specific
• When you want the code to be explicitly clear for other developers

Type Annotations — Adding Types to Your Code

A type annotation is the colon followed by the type name that you add after a variable, parameter, or function return value. It's the core syntax of TypeScript.

The annotation pattern:

let variableName: TypeName = value;
//              ^^^^^^^^^^
//              This is the type annotation
let
firstName
: string
=
"Alice"
;
keyword
variable name
type annotation
assignment
value

Annotating Variables

// Annotated variable declarations
let username: string = "john_doe";
let score: number = 0;
let isOnline: boolean = false;

// Declare without value (must annotate!)
let winner: string;           // Will be assigned later
let totalPoints: number;      // Will be assigned later

// Later in the code...
winner = "Alice";             // ✅ String — matches annotation
totalPoints = 1500;           // ✅ Number — matches annotation
totalPoints = "one thousand"; // ❌ Error — must be number

Annotating DOM Elements

When selecting HTML elements with document.querySelector(), TypeScript isn't sure which specific type of element it is — it just knows it's either an Element or null (if nothing was found). You need to tell TypeScript what you expect using type assertions with the as keyword.

❌ Without type assertion (TypeScript gives errors):

// TypeScript doesn't know this is specifically an input
const num1Input = document.querySelector('#num1');

// ERROR: Property 'value' does not exist on type 'Element | null'
console.log(num1Input.value);

✅ With type assertion (tells TypeScript what type it is):

// Use 'as HTMLInputElement' to tell TypeScript it's an input element
const num1Input = document.querySelector('#num1') as HTMLInputElement;

// Now TypeScript knows about .value, .type, .placeholder, etc.
console.log(num1Input.value);   // ✅ No error!

// Other common element types:
const myDiv = document.querySelector('#result') as HTMLDivElement;
const myBtn = document.querySelector('#addBtn') as HTMLButtonElement;
const myLink = document.querySelector('a') as HTMLAnchorElement;

Common HTML Element Types

HTMLInputElement →
HTMLButtonElement →
HTMLDivElement →
HTMLParagraphElement →

HTMLAnchorElement →
HTMLSelectElement →