Type script for begginers
TypeScript for Beginners: What, Why, and How to Use It
Welcome to our beginner guide to TypeScript! If you're just starting out and want to understand what TypeScript is and how to use it with JavaScript projects — this is for you.
💡 What is TypeScript?
TypeScript is a programming language built on top of JavaScript. It adds something very important: types.
Think of it as “JavaScript with extra safety and better tools.”
- ✅ Helps catch errors before you even run the code
- ✅ Makes your code easier to understand and work with
- ✅ Great for teams and long-term projects
And the best part? TypeScript becomes regular JavaScript when it runs, so it works anywhere JavaScript does!
⚙️ How to Install TypeScript
You can install TypeScript globally using npm (Node Package Manager). Open your terminal and type:
npm install -g typescript
Now you can check it worked:
tsc --version
🏁 Start a New TypeScript Project
- Create a new folder:
- Initialize a Node.js project (optional but recommended):
- Install TypeScript locally in the project:
- Create a TypeScript config file:
- Create a file named
index.ts
and write your code inside.
mkdir my-ts-app
cd my-ts-app
npm init -y
npm install --save-dev typescript
npx tsc --init
To compile the TypeScript to JavaScript, run:
npx tsc
That will generate an index.js
file that you can run with Node.js or in the browser.
🔤 TypeScript vs JavaScript Example
JavaScript:
function greet(name) {
return "Hello, " + name;
}
TypeScript:
function greet(name: string): string {
return "Hello, " + name;
}
We added : string
to say that name
must be a string, and the function returns a string. If someone calls greet(123)
, TypeScript will warn you! 🔥
🧱 Basic TypeScript Concepts
📌 Variables with Types
let age: number = 30;
let username: string = "Alice";
let isAdmin: boolean = true;
📌 Arrays
let fruits: string[] = ["apple", "banana", "orange"];
📌 Functions
function add(a: number, b: number): number {
return a + b;
}
📌 Objects
let user: { name: string; age: number } = {
name: "Bob",
age: 25
};
📌 Interfaces (for reusable types)
interface User {
name: string;
age: number;
}
let newUser: User = {
name: "Charlie",
age: 28
};
🔠 More About Types in TypeScript
Types are the core of TypeScript — they help us tell the computer what kind of data we expect. Here are the most common ones you'll use:
Type | Example | What It Means |
---|---|---|
string |
let name: string = "Bella"; |
A sequence of text characters |
number |
let age: number = 5; |
Any number: 1, 5.5, -10, etc. |
boolean |
let isCute: boolean = true; |
True or false |
any |
let anything: any = "Hello"; |
Anything goes (avoid if possible!) |
string[] |
let colors: string[] = ["red", "green"]; |
Array of strings |
💡 Pro tip: Use specific types as much as possible. It keeps your code safe!
🔁 Loops in TypeScript
Loops help us repeat actions. TypeScript loops are the same as JavaScript — but you can add types to the variables inside.
👉 For loop
for (let i: number = 0; i < 5; i++) {
console.log("i is", i);
}
👉 For...of (great for arrays)
let animals: string[] = ["dog", "cat", "parrot"];
for (let pet of animals) {
console.log("Pet:", pet);
}
👉 For...in (for object keys)
let user = { name: "Luna", age: 3 };
for (let key in user) {
console.log(key + ":", user[key as keyof typeof user]);
}
🛠️ Function Types
In TypeScript, you can describe exactly what kind of data your function takes in and what it gives back.
✅ Basic Function
function greet(name: string): string {
return "Hello, " + name;
}
✅ Function with multiple parameters
function multiply(a: number, b: number): number {
return a * b;
}
✅ Function that returns nothing (void)
function logMessage(message: string): void {
console.log("📣", message);
}
✅ Arrow function with types
const add = (x: number, y: number): number => {
return x + y;
}
🔍 Regular Function vs Arrow Function
TypeScript (like JavaScript) supports two main ways to write functions:
- Regular function: The old-school, flexible way
- Arrow function: A newer, shorter way (introduced in ES6)
✅ Regular Function
function sayHello(name: string): string {
return "Hello, " + name;
}
✅ This works well in most cases and lets you use this
the traditional way.
✅ Arrow Function
const sayHello = (name: string): string => {
return "Hello, " + name;
}
✅ Same result, but a shorter syntax.
⚠️ The Real Difference: this
Keyword
The biggest difference between the two is how they handle this
.
- Regular functions have their own
this
. - Arrow functions use the
this
from the place they were defined (they don't create a newthis
).
Let’s look at an example 👇
const person = {
name: "Luna",
speakRegular: function () {
console.log("Regular:", this.name);
},
speakArrow: () => {
console.log("Arrow:", this.name);
}
};
person.speakRegular(); // ✅ "Luna"
person.speakArrow(); // ❌ undefined (or window/global)
Why? Because this
in speakArrow
doesn't refer to person
, but to the outer/global context.
🧠 So When Should You Use Each?
- 👉 Use arrow functions for short, inline functions or callbacks (like in
.map
,.filter
, etc.) - 👉 Use regular functions when you need your own
this
context — like in class methods or object methods
Example in an array:
const names: string[] = ["Bella", "Max", "Luna"];
const greetings = names.map(name => "Hi, " + name);
console.log(greetings); // ["Hi, Bella", "Hi, Max", "Hi, Luna"]
💬 Summary
Aspect | Regular Function | Arrow Function |
---|---|---|
this behavior |
Has its own this |
Uses outer this |
Syntax | Longer | Shorter |
Best for | Methods and complex logic | Callbacks and inline logic |
🧩 Optional Parameters
You can make parameters optional using ?
function greetUser(name: string, greeting?: string): string {
return (greeting || "Hello") + ", " + name;
}
Examples:
greetUser("Alice") // "Hello, Alice"
greetUser("Bob", "Hi") // "Hi, Bob"
🧱 Type Aliases
Sometimes your types get long or repeated. You can name them using type
or interface
.
type Dog = {
name: string;
age: number;
isGoodBoy: boolean;
};
let myDog: Dog = {
name: "Buster",
age: 4,
isGoodBoy: true
};
🎯 Summary (New Concepts)
- 📌 Use types to describe your variables and functions
- 🔁 Use loops to repeat logic — same as JavaScript, but with type safety
- 🛠️ Use function types to catch errors when passing the wrong data
- 💼 Use type aliases to keep your code clean and reusable
💡 Why Use TypeScript?
- 🛡️ Fewer bugs — you’ll catch mistakes before running the code
- 📘 Better documentation — types tell you what each part expects
- 🤝 Easier collaboration — helps you and your partner understand each other’s code
👣 What’s Next?
➡️ Learn about type narrowing (e.g. checkingtypeof
)➡️ Explore enums and union types
➡️ Try using TypeScript in a React project or Node.js app
We're just getting started — and you're doing great! 🚀
Stay curious and keep learning. 💙
📌 Pro Tip
Use a code editor like VS Code — it works perfectly with TypeScript and shows helpful hints while you type.
🧠 Final Words
TypeScript might seem like “extra work” at first, but it saves you time and headaches later — especially when working with others. It makes your code cleaner, safer, and easier to grow.
Once you try it, you’ll wonder how you ever coded without it. 😄
Aspect | Regular Function | Arrow Function |
---|---|---|
this behavior |
Has its own this |
Uses outer this |
Syntax | Longer | Shorter |
Best for | Methods and complex logic | Callbacks and inline logic |
Comments
Post a Comment