Text
stringUsed for words, names, or letters.
let name: string = "Sam";
TypeScript is a tool that adds strict rules to JavaScript. It finds your mistakes before you even run your code.
let message: string = "Hello World!";
message = 5;
// 🛑 ERROR: You said it was a string!
// You cannot put a number here.
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.
let userAge = 25;
// JavaScript lets you do this:
userAge = "twenty-five";
// JavaScript lets you do this too:
userAge = true;
// This causes bugs later!
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.
"This box is only for numbers."
You try to put a word in the box.
A red line appears before you even save.
Web browsers (like Chrome or Safari) do not understand TypeScript. They only understand JavaScript. So, how does it work?
You write TypeScript
With all the rules and safety checks.
It becomes JavaScript
The rules are removed, and safe code goes to the browser.
When you create a box (a variable) to hold data, you put a colon : and then name the rule.
Used for words, names, or letters.
let name: string = "Sam";
Used for amounts, ages, or prices.
let price: number = 99;
Used for true or false switches.
let isOpen: boolean = true;
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.
let colors: string[] = ["red", "blue"];
// This works perfectly
colors.push("green");
let colors: string[] = ["red", "blue"];
// 🛑 TypeScript will block this!
colors.push(500);
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.
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).
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.
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!
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" };
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!
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";
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"];
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";
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";
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());
}
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.
function multiply(a, b) {
return a * b;
}
// JS will try to multiply a word by a number.
// The app will break.
multiply("hello", 10);
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);
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!
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.
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.
Open your computer terminal and run this command to download TypeScript.
npm install -g typescript
Create a file ending in .ts and write your rules.
// app.ts
let age: number = 20;
Run this command to turn your .ts file into a plain .js file.
tsc app.ts