A class in TypeScript defines a blueprint for creating objects with:
Properties (state)
Methods (behavior)
A constructor for initialization
✅ Basic Class with Constructor
class Person {
name: string;
age: number;
// Constructor
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): void {
console.log(`Hello, my name is ${this.name}.`);
}
}
const p1 = new Person("Codeveda", 21);
p1.greet(); // Hello, my name is Codeveda.📦 Constructor Parameters
You can annotate the types of constructor parameters.
Inside the constructor, you assign those values to class properties using
this.
🔐 Access Modifiers (Public, Private, Protected)
You can control access to class members:
class User {
public name: string;
private password: string;
protected role: string;
constructor(name: string, password: string, role: string) {
this.name = name;
this.password = password;
this.role = role;
}
login(): string {
return `${this.name} logged in`;
}
}
const user = new User("Bhaskar", "secret123", "Admin");
console.log(user.name); //Bhaskar
console.log(user.password); //Error: Can't be accessed because it is Private
console.log(user.role); //Error: Can't be accessed because it is Protected
console.log(user.login()); //Bhaskar logged in✨ Shortcut: Declare and Assign in Constructor
You can combine property declaration and initialization directly in the constructor:
class Product {
constructor(
public name: string,
private price: number
) {}
getPrice(): number {
return this.price;
}
}
const product = new Product("Laptop", 50000);
console.log(product.name); // Laptop
console.log(product.getPrice()); // 50000
console.log(product.price); // ❌ ErrorThis avoids writing this.name = name etc.
🔁 Class with Methods
class Circle {
radius: number;
constructor(radius: number) {
this.radius = radius;
}
getArea(): number {
return Math.PI * this.radius ** 2;
}
}
const c = new Circle(5);
console.log(c.getArea()); // 78.54...🧠 Optional & Readonly Properties
class Book {
readonly id: number; //Readonly
title: string;
author?: string; //Optional
constructor(id: number, title: string, author?: string) {
this.id = id;
this.title = title;
this.author = author;
}
}✅ Summary Table
Feature | Syntax Example |
|---|---|
Define class |
|
Constructor |
|
Property types |
|
Access modifiers |
|
Optional prop |
|
Readonly prop |
|
Shortcut props |
|