Today! We’re going to Continue TypeScript learning like you’re a smart 5-year-old who loves to build things and asks “why?” (which is the best thing ever).
& yes “why?” is my way of learning.
I've divided this into 20 Chapters. and will go one by one and each will be of 2 - 3 min. of read.
This is a Continuation, if you have not read Previous chapter - Chapter 2
This is Chapter ⓷ TS Mastering
🧩 Chapter 3: Managing Functions with Typescript!
(aka: “Telling your helpers what kind of stuff they’ll handle”)
🍳 Imagine this:
You have a kitchen robot 🧑🍳🤖
You tell it:
“Make me a sandwich with bread and cheese.”
But what if you accidentally say:
“Make me a sandwich with rocks and batteries”? 🪨🔋😨
In JavaScript, the robot might try to do it.
But in TypeScript, it says:
❌ “Hey! That’s not sandwich stuff!”
🛠️ Let’s build a function with types!
Without TypeScript (JavaScript):
function add(a, b) {
return a + b;
}
add(5, "10"); // Uh oh! Output is "510"
With TypeScript:
function add(a: number, b: number): number {
return a + b;
}
add(5, 10); // ✅ OK!
add(5, "10"); // ❌ Error! TS says: "I expected a number, not a string"
🧙♂️ Parts of a Typed Function:
function greet(name: string): string {
return "Hello, " + name;
}
-
name: string
→ input must be a string -
: string
after the)
→ function returns a string
💡 What if a function returns nothing?
That’s called void
:
function logMessage(msg: string): void {
console.log("Message:", msg);
}
Think of void
like: “I’m just doing stuff, not giving anything back.”
🪄 Default and Optional Parameters
function greet(name: string = "friend") {
console.log("Hi", name);
}
function greetAgain(name?: string) {
console.log("Hello", name ?? "buddy");
}
-
=
means default -
?
means it’s optional
🧪 Example:
function multiply(a: number, b: number): number {
return a * b;
}
const result = multiply(3, 4); // result is 12 ✅
Try changing 4
to "4"
and see TypeScript stop you. 🛑
If you enjoyed this and want to master TypeScript and other technologies, follow the series and drop a like!🤝
I’m a passionate software developer sharing the cool things I discover, hoping they help you level up on your coding journey.
How i created my own State Management Library : Rethinking State Management in React — From a Dev, for Developers.