Skip to main content

Classes and Constructors

Level: Beginner

ℹ️ What You'll Learn
  • Class syntax and constructors
  • Property declarations with types
  • Access modifiers: public, private, protected
  • Methods and this context
  • Class inheritance
  • Super keyword for parent calls
  • Static members and methods
  • SMS Student and Teacher classes

Why This Matters

Classes and Constructors helps you write safer frontend code. In ASP.NET Core projects, TypeScript makes API response shapes, form models, DOM values, and reusable helpers easier to maintain.

Object-oriented programming with TypeScript classes.

The Problem

JavaScript allows many mistakes to appear only at runtime. This lesson shows how Classes and Constructors lets TypeScript catch wrong values, missing properties, and unsafe assumptions before the page reaches users.

Basic Class

class Student {
id: number;
name: string;
email: string;
className: string;

constructor(id: number, name: string, email: string, className: string) {
this.id = id;
this.name = name;
this.email = email;
this.className = className;
}
}

const student = new Student(101, "Ravi Kumar", "ravi@example.com", "10");
console.log(student.name); // "Ravi Kumar"

Properties and Methods

class Student {
id: number;
name: string;
marks: number[];

constructor(id: number, name: string) {
this.id = id;
this.name = name;
this.marks = [];
}

// Method
addMarks(mark: number): void {
this.marks.push(mark);
}

// Method with return
getAverage(): number {
const sum = this.marks.reduce((a, b) => a + b, 0);
return sum / this.marks.length;
}

// Method returns object
getDetails(): { name: string; average: number } {
return {
name: this.name,
average: this.getAverage()
};
}
}

const student = new Student(101, "Ravi");
student.addMarks(95);
student.addMarks(88);
console.log(student.getAverage()); // 91.5

Access Modifiers

class Student {
public id: number; // Accessible everywhere
private password: string; // Only inside class
protected status: string; // Inside class + subclasses

constructor(id: number, password: string, status: string) {
this.id = id;
this.password = password;
this.status = status;
}

verifyPassword(pwd: string): boolean {
return this.password === pwd;
}
}

const student = new Student(101, "secret", "Active");
console.log(student.id); // OK
console.log(student.password); // Error - private
student.verifyPassword("secret"); // OK

Parameter Properties

// Shorthand - declare and initialize in constructor
class Student {
constructor(
public id: number,
public name: string,
public email: string,
private password: string
) {}
}

const student = new Student(101, "Ravi", "ravi@example.com", "secret");
console.log(student.name); // "Ravi"

Static Members

class School {
static schoolName = "NexCoding Academy";
static count = 0;

name: string;

constructor(name: string) {
this.name = name;
School.count++;
}

static getInfo(): string {
return `${School.schoolName} has ${School.count} schools`;
}
}

console.log(School.schoolName); // "NexCoding Academy"
console.log(School.getInfo()); // "NexCoding Academy has 1 schools"

Inheritance

class Person {
name: string;
email: string;

constructor(name: string, email: string) {
this.name = name;
this.email = email;
}

greet(): string {
return `Hello ${this.name}`;
}
}

class Student extends Person {
className: string;
marks: number[];

constructor(name: string, email: string, className: string) {
super(name, email); // Call parent constructor
this.className = className;
this.marks = [];
}

getAverage(): number {
return this.marks.reduce((a, b) => a + b, 0) / this.marks.length;
}
}

const student = new Student("Ravi", "ravi@example.com", "10");
console.log(student.greet()); // "Hello Ravi" (inherited)

SMS Example

class StudentManager {
private students: Student[] = [];

addStudent(student: Student): void {
this.students.push(student);
}

getStudent(id: number): Student | undefined {
return this.students.find(s => s.id === id);
}

getAllStudents(): Student[] {
return this.students;
}

updateStudentStatus(id: number, status: string): void {
const student = this.getStudent(id);
if (student) {
student.status = status;
}
}

deleteStudent(id: number): void {
this.students = this.students.filter(s => s.id !== id);
}
}

interface Student {
id: number;
name: string;
className: string;
status: string;
}

const manager = new StudentManager();
manager.addStudent({ id: 101, name: "Ravi", className: "10", status: "Active" });
manager.addStudent({ id: 102, name: "Priya", className: "10", status: "Active" });

console.log(manager.getAllStudents());
manager.updateStudentStatus(101, "Inactive");

Key Takeaways

  • Classes organize code and data
  • Constructors initialize objects
  • Methods are functions in classes
  • Access modifiers control visibility
  • Inheritance reuses code
  • Static members belong to class, not instances
  • Next: Generics
💡 Backend Developer Tip

Classes in TypeScript are similar to C# classes. Mirror your backend classes - User class becomes User class in TypeScript.

⚠️ Class Mistakes
  1. Using public for everything — No encapsulation
  2. Forgetting super() in inheritance — Parent not initialized
  3. Not using access modifiers — Data exposed unnecessarily
  4. Static for instance data — Data shared incorrectly
🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on TypeScript Classes. Try these prompts:

  • "Why use classes instead of objects?"
  • "What's difference between public/private?"
  • "When use static members?"
  • "Quiz me on classes"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

Quick Definitions

  • Classes and Constructors - The main TypeScript concept explained in this lesson.
  • Type - A rule that describes what kind of value is allowed.
  • Interface - A contract that describes the shape of an object.
  • DTO model - The frontend shape of data coming from ASP.NET Core Web API.

Common Mistakes

  • Using any instead of defining a useful type
  • Making types too complex before understanding the data
  • Forgetting that API data still needs runtime validation
  • Confusing JavaScript runtime behavior with TypeScript compile-time checks
  • Not reusing shared types for repeated API models

Practice Task

Create a small TypeScript example using Classes and Constructors. Keep it connected to a School Management System scenario.

Suggested practice:

  1. Define a Student, Teacher, Attendance, or Marks model.
  2. Write one function or class using that type.
  3. Add one intentionally wrong value and read the TypeScript error.
  4. Fix the type or the data shape.
  5. Explain the type contract in your own words.

Quick Revision

QuestionAnswer
What is the main idea?Use TypeScript to make Classes and Constructors safer and clearer.
Where is it used?API models, forms, DOM code, helpers, and React/Next.js apps.
What should beginners avoid?Overusing any and ignoring API validation.
What is the best debugging habit?Read the TypeScript error and compare it with the expected data shape.
🎯 How would you explain Classes and Constructors in an interview?

Classes and Constructors is a TypeScript concept that improves JavaScript safety by making data shapes and function expectations clear. I would explain the problem it solves, show a small example, and mention how it helps with API-connected frontend code.

🎯 Where is this used in real projects?

It is used in API DTOs, form models, DOM access, helper functions, React props, service classes, and reusable frontend utilities.

Next Article

Generics ->

nexcoding.in