TypeScript Classes
TypeScript: Classes
Classes in TypeScript are blueprints for creating objects with structure, behavior, and built-in type safety.
What is a Class?
A class is like a template. It lets you group together variables (called properties) and functions (called methods) into a single unit that represents a thing—like a person, a car, or a user.
Basic Class Example
class Car {
brand: string;
speed: number;
constructor(brand: string, speed: number) {
this.brand = brand;
this.speed = speed;
}
drive(): void {
console.log(`${this.brand} is driving at ${this.speed} km/h`);
}
}
- brand and speed are properties
- constructor sets initial values when you create a new object
- drive() is a method (a function inside a class)
Creating an Object
const myCar = new Car("Toyota", 120);
MyCar.drive(); // Output: Toyota is driving at 120 km/h
The new keyword is used to create an instance (object) from the class.
Access Modifiers
TypeScript lets you control how properties are accessed using:
- public → accessible from anywhere
- private → only inside the class
- protected → inside the class and subclasses
Here, balance is hidden from outside access directly.
Inheritance
Classes can extend other classes to reuse code:
Now Dog has both move() and bark().
Interfaces with Classes
You can force a class to follow a specific structure using implements:
interface Person {
name: string;
speak(): void;
}
class Student implements Person {
name: string;
constructor(name: string) {
this.name = name;
}
speak(): void {
console.log(`${this.name} is speaking`);
}
}
Shorthand Property Declaration
You can declare and assign class properties right in the constructor:
class Book {
constructor(public title: string, private author: string) {}
}
This auto-creates title and author with the right access level.
Why Use Classes?
- Organize code in a neat, object-based structure
- Encapsulate logic inside reusable components
- Inherit common behavior for different object types
- Enable strict typing for safer, smarter code
Prefer Learning by Watching?
Watch these YouTube tutorials to understand TYPESCRIPT Tutorial visually:
What You'll Learn:
- 📌 TypeScript Classes
- 📌 TypeScript Tutorial #12 - Classes