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 3
This is Chapter ⓸ TS Mastering
🧩 Chapter 5: Type Aliases & Interfaces
(aka: “Why repeat yourself when you can name your thing once?”)
🎭 Imagine this:
You keep writing this:
let person: { name: string; age: number; isCool: boolean }
over and over and over again... 🥱
Wouldn’t it be cool to say:
“Let’s call a common type for
Person
!”
✅ Type Aliases – Give a shape a nickname
Think of it like, using a same type instance for similar type of objects.
Here Both, me and friend is of type - Person
type Person = {
name: string;
age: number;
isCool: boolean;
};
let me: Person = {
name: "Karandeep Singh",
age: 25,
isCool: true,
};
let friend: Person = {
name: "some name",
age: 25,
isCool: true,
};
Now, instead of rewriting the full type again & again, just say :Person
as the type for every person object you create.
🤝 Interfaces – Like type
, but for teamwork!
interface Car {
brand: string;
speed: number;
electric?: boolean; // optional
}
let myCar: Car = {
brand: "BMW M5",
speed: 200,
};
Interfaces are great when many people or pieces of code work together, like a contract everyone agrees on 🤝
🥊 Type vs Interface: What’s the difference?
Feature | type |
interface |
---|---|---|
Used for | Anything | Mostly for objects/classes |
Can extend | ✅ Yes (& ) |
✅ Yes (extends ) |
Can merge | ❌ No | ✅ Yes (declaration merge) |
Can do unions | ✅ Yes (A - B ) |
❌ Not directly |
For most cases, either works fine — go with what feels good!
🔧 Extending Types – Inheritance!
type Animal = {
name: string;
};
type Dog = Animal & {
barkVolume: number;
};
let d: Dog = {
name: "Bruno",
barkVolume: 8,
};
OR using interface:
interface Animal {
name: string;
}
interface Dog extends Animal {
barkVolume: number;
}
Both ways say:
"Dog is like Animal… plus extra properties"
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.