🏛️ TypeScript — Classes: Build Object-Oriented Code with Type Safety
🧲 Introduction – What Are Classes in TypeScript?
In TypeScript, a class is a blueprint for creating objects with shared structure and behavior. Classes allow you to write object-oriented code using familiar constructs like inheritance, constructors, access modifiers, properties, and methods—all enhanced with TypeScript’s strong type system.
🎯 In this guide, you’ll learn:
- How to define and use classes in TypeScript
- Class properties, constructors, and methods
- Access modifiers:
public
,private
,protected
- Inheritance, method overriding, and super calls
- Real-world use cases and best practices
🏗️ Declaring a Class in TypeScript
✅ Basic Syntax:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): void {
console.log(`Hello, my name is ${this.name}`);
}
}
const user = new Person("Alice", 30);
user.greet(); // Hello, my name is Alice
✅ Explanation:
- The class defines two properties (
name
,age
) and one method (greet
) constructor
initializes object valuesthis
refers to the current instance
🔐 Access Modifiers – Control Property Visibility
TypeScript supports the following access levels:
Modifier | Scope |
---|---|
public | Accessible from anywhere (default) |
private | Accessible only within the class |
protected | Accessible within the class and its subclasses |
✅ Example:
class Employee {
public name: string;
private salary: number;
constructor(name: string, salary: number) {
this.name = name;
this.salary = salary;
}
getSalary(): number {
return this.salary;
}
}
const emp = new Employee("Bob", 50000);
// emp.salary = 60000; // ❌ Error: 'salary' is private
console.log(emp.getSalary()); // ✅ Allowed via method
🧱 Readonly Properties
Use readonly
to make a class property immutable after initialization.
class Config {
readonly apiKey: string;
constructor(apiKey: string) {
this.apiKey = apiKey;
}
}
const config = new Config("XYZ123");
// config.apiKey = "ABC"; // ❌ Error
🧬 Inheritance – Extend Functionality
Use the extends
keyword to create a subclass and inherit properties and methods.
class Animal {
move() {
console.log("Animal is moving...");
}
}
class Dog extends Animal {
bark() {
console.log("Woof!");
}
}
const pet = new Dog();
pet.move(); // inherited
pet.bark(); // subclass-specific
🔁 Method Overriding & super()
You can override methods from the base class and call the parent using super
.
class Vehicle {
start() {
console.log("Starting vehicle...");
}
}
class Car extends Vehicle {
start() {
super.start();
console.log("Starting car engine...");
}
}
const car = new Car();
car.start();
✅ Output:
Starting vehicle...
Starting car engine...
🧩 Parameter Properties (Short Syntax)
You can declare and initialize properties directly in the constructor:
class User {
constructor(public username: string, private password: string) {}
}
✅ This shorthand automatically adds username
and password
as class properties.
🧠 Static Properties and Methods
Static members belong to the class itself, not instances.
class MathHelper {
static PI: number = 3.14159;
static square(n: number): number {
return n * n;
}
}
console.log(MathHelper.PI);
console.log(MathHelper.square(5));
🧰 Getters and Setters
Use get
and set
to create controlled access to class properties.
class BankAccount {
private _balance: number = 0;
get balance(): number {
return this._balance;
}
set balance(amount: number) {
if (amount >= 0) {
this._balance = amount;
}
}
}
🔄 Implementing Interfaces in Classes
Classes can implement interfaces to enforce structure.
interface Printable {
print(): void;
}
class Document implements Printable {
print() {
console.log("Printing document...");
}
}
🔍 Real-World Use Cases
- Modeling business logic (e.g.,
Invoice
,Order
,User
) - Implementing design patterns (e.g., Singleton, Factory)
- Building UI components with typed state and behavior
- Encapsulating services, utilities, and reusable modules
⚠️ Common Mistakes & How to Avoid Them
❌ Mistake | ✅ Solution |
---|---|
Forgetting to initialize properties | Use constructors or default values |
Using this outside methods | Bind or call within method scope |
Accessing private members outside | Use public methods or accessors instead |
Ignoring types in constructor | Annotate constructor parameters for type safety |
💡 Best Practices for Using Classes in TypeScript
- ✅ Always define property types explicitly
- ✅ Use
private
andreadonly
to enforce encapsulation - ✅ Favor interface implementation for type contracts
- ✅ Avoid large monolithic classes—break into smaller units
- ✅ Use inheritance judiciously; prefer composition when possible
📌 Summary – Recap & Next Steps
Classes in TypeScript bring structure, encapsulation, and strong typing to your object-oriented code. With support for inheritance, access control, static methods, and more, classes help model real-world entities effectively.
🔍 Key Takeaways:
- Define object structure using properties and methods
- Use
constructor
to initialize values - Leverage access modifiers (
public
,private
,protected
) for control - Extend base classes using
extends
andsuper()
- Use
static
,get/set
, and interfaces for advanced class design
⚙️ Real-world relevance: Classes are essential in UI components, data models, backend services, design patterns, and enterprise-scale TypeScript applications.
❓ FAQs – Classes in TypeScript
❓ Can TypeScript classes implement multiple interfaces?
✅ Yes. Use commas: class MyClass implements A, B {}
❓ What is the difference between private
and protected
?private
is accessible only within the class. protected
is also accessible in derived classes.
❓ Are classes available at runtime?
✅ Yes. Unlike interfaces or types, classes compile to JavaScript and exist at runtime.
❓ Can I define a class without a constructor?
✅ Yes. If you don’t need initial values, a constructor is optional.
❓ Should I use class or interface for data modeling?
📌 Use interfaces for type definition, and classes for instantiating behavior.
Share Now :