Enhance your JavaScript development with static types and modern language features.
Topic: TypeScript
Stop Guessing. Start Knowing.
TypeScript is a tool that adds strict rules to JavaScript. It finds your mistakes before you even run your code.
No more bad surprises.
let message: string = "Hello World!";
message = 5;// 🛑 ERROR: You said it was a string!// You cannot put a number here.
The Problem with JavaScript
JavaScript is too relaxed. It lets you do things that make no sense. It does not check your work while you type. It only fails when you try to run it.
Imagine trying to add the word "apple" to the number 5. JavaScript will just say "5apple" instead of telling you it is a bad idea.
Plain JavaScript Example
let userAge = 25;
// JavaScript lets you do this:
userAge = "twenty-five";
// JavaScript lets you do this too:
userAge = true;
// This causes bugs later!
The TypeScript Fix
TypeScript adds Types. A "type" is a rule. You tell TypeScript exactly what kind of data is allowed inside a box. If you try to put the wrong data in the box, TypeScript stops you instantly.
1. You set a rule
"This box is only for numbers."
2. You make a mistake
You try to put a word in the box.
3. TypeScript warns you
A red line appears before you even save.
The Translator Step
Web browsers (like Chrome or Safari) do not understand TypeScript. They only understand JavaScript. So, how does it work?
file.ts
You write TypeScript
With all the rules and safety checks.
Compiler
file.js
It becomes JavaScript
The rules are removed, and safe code goes to the browser.
The Three Basic Rules
When you create a box (a variable) to hold data, you put a colon : and then name the rule.
Text
string
Used for words, names, or letters.
let name: string = "Sam";
Math
number
Used for amounts, ages, or prices.
let price: number = 99;
Yes / No
boolean
Used for true or false switches.
let isOpen: boolean = true;
Rules for Lists (Arrays)
If you want a list of items, you must tell TypeScript what kind of items are allowed in the list. You add [] to the end of the rule.
Safe List of Words
let colors: string[] = ["red", "blue"];
// This works perfectly
colors.push("green");
Broken Rule
let colors: string[] = ["red", "blue"];
// 🛑 TypeScript will block this!
colors.push(500);
Making Custom Shapes (Interfaces)
Sometimes you have complex data, like a User. A User might have a name (text) and an age (number). You can create a custom rule for this shape using the word interface.
Step 1: Make the Rule
interface User {
name: string;
age: number;
}
We just created a rule called "User". Anyone labeled as a User MUST have a name (words) and an age (math).
Step 2: Use the Rule
let player1: User = {
name: "Tom",
age: 30
};
If you forget to add the age, or if you make the age a word ("thirty"), TypeScript will instantly warn you.
Rules for Actions (Functions)
A function is like a machine in a factory. You put ingredients in, and a product comes out. TypeScript lets you set rules for the ingredients (Inputs) AND the final product (Output).
// (Input 1, Input 2) : Output Rule
function addNumbers(a: number, b: number): number {
return a + b;
}
If the machine tries to output a word instead of a number, TypeScript will stop it!
The "Maybe" Rule (Optional)
Sometimes a piece of data is not required. For example, some people have a middle name, and some do not. You can make a rule optional by adding a question mark ?.
interface Profile {
firstName: string;
middleName?: string; // <-- The question mark means "optional"
}
// Both of these are 100% legal:
let person1: Profile = { firstName: "John" };
let person2: Profile = { firstName: "John", middleName: "Robert" };
The "Or" Rule (Union Types)
What if a box is allowed to hold a number OR a word? You can combine rules using the straight line pipe symbol |. It acts exactly like the word "Or".
// This box accepts a number OR a word
let score: number | string;
score = 100; // Works!
score = "Winner"; // Works!
score = true; // 🛑 ERROR: Not a number or a word!
Nicknames for Rules (Type Aliases)
If your "Or" rules get too long and messy, you can create a customized nickname for them using the word type. This makes your code much easier to read.
1. Create the Nickname
type ID = string | number;
2. Use the Nickname anywhere
let playerID: ID = 99;
let adminID: ID = "ADMIN-A1";
Very Strict Lists (Tuples)
Normal arrays let you put things in any order. But a Tuple is a special list where the exact order and exact size matter. Think of it like a train: the engine must come first, then the passenger car.
// Rule: EXACTLY one word, followed by EXACTLY one number.
let myTrain: [string, number];
myTrain = ["Engine", 100]; // Correct.// 🛑 ERROR: The order is backwards!
myTrain = [100, "Engine"];
// 🛑 ERROR: Too many items!
myTrain = ["Engine", 100, "Extra Car"];
Look, But Do Not Touch (Readonly)
Sometimes you have data that should never, ever change (like a user's birthday). You can lock it inside a glass case using the word readonly.
interface Account {
readonly username: string;
}
let user: Account = { username: "cool_kid_99" };
// 🛑 ERROR: It is locked! You cannot change a readonly item.
user.username = "hacker_man";
Exact Matches (Literal Types)
Instead of saying "any word is allowed", you can tell TypeScript that only specific, exact words are allowed.
// The traffic light can ONLY be these 3 exact words.
let trafficLight: "red" | "yellow" | "green";
trafficLight = "green"; // Works!// 🛑 ERROR: "purple" is not on the allowed list!
trafficLight = "purple";
The Mystery Box (unknown)
Sometimes you download data from the internet and you honestly do not know what it is yet. Instead of turning off all rules, use the word unknown. It means "This is a mystery box. I must check what is inside before I use it."
let mysteryBox: unknown = "I am a secret";
// TypeScript will STOP you from using it blindly:// mysteryBox.toUpperCase(); <-- 🛑 ERROR! You didn't check it first!if (typeof mysteryBox === "string") {
// Now TypeScript knows it is safe to use as a word!
console.log(mysteryBox.toUpperCase());
}
The Editor Magic (Autocomplete)
Because TypeScript knows all the rules and shapes of your data, it acts like a magical assistant in your code editor. When you type a dot ., it instantly pops up a menu showing you exactly what is allowed. You don't have to memorize anything!
user.
firstNamestring
lastNamestring
agenumber
Side by Side Comparison
JavaScriptAllows silly mistakes.
function multiply(a, b) {
return a * b;
}
// JS will try to multiply a word by a number.
// The app will break.
multiply("hello", 10);
TypeScriptForces correct usage.
function multiply(a: number, b: number) {
return a * b;
}
// 🛑 TS instantly highlights "hello" in red.
// It will not let you save this mistake.
multiply("hello", 10);
The Danger Word: "any"
Never use the rule called any.
If you set a variable to any, you are telling TypeScript to turn off all the rules for that box. It becomes just like normal JavaScript again, and bugs will sneak in.
// ❌ This is bad practice. You lose all safety.
let data: any = "Hello"; data = 500; // No warning... danger!
Why Big Teams Love It
No Need to Guess
When 10 people work on the same website, it gets messy. Someone else might write a function, and you don't know what kind of data it needs.
Built-in Instructions
With TypeScript, the rules tell you exactly what is required. It is like the code comes with an instruction manual built directly into it. It is very easy to grow the project safely.
Your Quick Cheat Sheet
Words
string
Numbers
number
Yes/No
boolean
Lists
[]
Or
|
Optional
?
Avoid
any
Shapes
interface
How to Start Today
1
Install the tool
Open your computer terminal and run this command to download TypeScript.
npm install -g typescript
2
Write your code
Create a file ending in .ts and write your rules.
// app.ts
let age: number = 20;
3
Translate it
Run this command to turn your .ts file into a plain .js file.
tsc app.ts
More in this series
Master more skills with other tutorials from the Web Development series.