Tutorials Logic, IN info@tutorialslogic.com

TypeScript Classes: Access Modifiers, Constructors and Implements

TypeScript Classes

TypeScript classes add type checking to JavaScript class syntax. They help you model objects that combine data and behavior, such as users, invoices, carts, repositories, services, UI components, and domain entities.

A TypeScript class can use constructors, public/private/protected members, readonly properties, getters, setters, static members, abstract classes, inheritance, and `implements` clauses. The goal is not to put everything into classes; the goal is to use classes when encapsulated state and behavior make the code clearer.

TypeScript is expanded here with a practical explanation, multiple examples, and beginner-focused checks so the idea is easier to learn from this page alone.

Read the concept first, then trace the example line by line. The important habit is to connect the rule to visible behavior instead of memorizing only the name.

Class Basics

A class is a blueprint for objects. The constructor initializes each instance, methods define behavior, and properties store instance data. TypeScript checks that values assigned to properties match their declared types.

  • `public` members can be used anywhere and are the default.
  • `private` members can only be used inside the class.
  • `protected` members can be used inside the class and subclasses.
  • `readonly` properties can be assigned during initialization but not changed later.
  • Parameter properties let you declare and assign constructor properties in one line.

Class With Access Modifiers

Class With Access Modifiers
class Course {
  private enrolled = 0;

  constructor(
    public readonly id: number,
    public title: string,
    private maxStudents: number
  ) {}

  enroll(): void {
    if (this.enrolled >= this.maxStudents) {
      throw new Error("Course is full");
    }
    this.enrolled++;
  }

  get seatsLeft(): number {
    return this.maxStudents - this.enrolled;
  }
}

const course = new Course(1, "TypeScript Classes", 30);
course.enroll();
console.log(course.title, course.seatsLeft);

Implements and Interfaces

The `implements` keyword checks that a class follows an interface shape. It does not copy code from the interface; it only verifies that the required members exist with compatible types.

  • Use interfaces to describe required behavior.
  • Use classes to provide implementation and state.
  • A class can implement multiple interfaces.
  • An interface cannot enforce private implementation details.

Class Implementing an Interface

Class Implementing an Interface
interface NotificationSender {
  send(to: string, message: string): Promise<void>;
}

class EmailSender implements NotificationSender {
  constructor(private fromAddress: string) {}

  async send(to: string, message: string): Promise<void> {
    console.log(`Email from ${this.fromAddress} to ${to}: ${message}`);
  }
}

async function notifyUser(sender: NotificationSender) {
  await sender.send("student@example.com", "Your course is ready.");
}

notifyUser(new EmailSender("noreply@tutorialslogic.com"));

Abstract Classes

An abstract class is useful when related classes share some implementation but must define certain methods themselves. It can hold common properties and methods while leaving specialized behavior to subclasses.

  • You cannot create an instance of an abstract class directly.
  • Abstract methods must be implemented by concrete subclasses.
  • Prefer interfaces when you only need a shape; use abstract classes when shared code is valuable.

Detailed Explanation of TypeScript

TypeScript becomes much easier when you separate the concept from the tool syntax. First identify the problem being solved, then identify the data or resource being changed, and finally identify the proof that the change worked.

In TypeScript, this topic should be studied through compile-time contracts, generic constraints, object shape, narrowing, and runtime validation. Those points explain not only how to use the feature, but also why it fails when the wrong assumption is made.

The previous audit note was: under 650 content words . This expanded section adds a fuller explanation, concrete examples, and practice guidance so the page can stand on its own for beginners.

A good way to learn this page is to read the normal path once, run or trace the example, then intentionally change one input to observe the different result. That one change teaches more than memorizing several definitions.

  • Write the goal of TypeScript before touching code or configuration.
  • Identify the normal case, edge case, and failure case.
  • Trace what changes before and after the operation.
  • Use a command, output, compiler message, log, metric, or table to verify the result.
  • Record the mistake that would confuse a beginner and the exact fix.

Beginner-Friendly Walkthrough for TypeScript

Start with a tiny project scenario. For example, imagine one user action, one request, one resource, one function call, or one batch of data. Keep the scenario small enough that every step can be explained without skipping details.

Next, describe the movement of information. Where does the input start? Which rule or component handles it? What result should appear? If the result is wrong, where would you inspect first?

Finally, compare two outcomes. The correct outcome proves that you understand the main rule. The incorrect outcome teaches the symptom, which is what you will recognize later during debugging or interviews.

  • Normal path: valid input produces the expected result.
  • Boundary path: the smallest, largest, empty, or unusual input still behaves predictably.
  • Error path: a realistic mistake creates a visible symptom.
  • Fix path: one focused correction removes the symptom without changing unrelated code.

Abstract Base Class

Abstract Base Class
abstract class ReportExporter {
  constructor(protected fileName: string) {}

  abstract extension(): string;
  abstract render(): string;

  outputPath(): string {
    return `${this.fileName}.${this.extension()}`;
  }
}

class CsvExporter extends ReportExporter {
  extension(): string {
    return "csv";
  }

  render(): string {
    return "name,total\nAsha,1200";
  }
}

const exporter = new CsvExporter("orders");
console.log(exporter.outputPath());
console.log(exporter.render());

TypeScript TypeScript type-safe example

TypeScript TypeScript type-safe example
type TypescriptState = {
  id: string;
  title: string;
  ready: boolean;
};

function markTypescriptReady(state: TypescriptState): TypescriptState {
  return { ...state, ready: true };
}

console.log(markTypescriptReady({ id: '1', title: 'TypeScript', ready: false }));

TypeScript TypeScript failure-prevention example

TypeScript TypeScript failure-prevention example
function requireNonEmptyTypescript(value: string): string {
  if (value.trim() === '') {
    throw new Error('TypeScript requires a non-empty value');
  }
  return value;
}

const checked = requireNonEmptyTypescript('demo');
console.log(checked);
Key Takeaways
  • Use classes when state and behavior belong together.
  • Use private/protected to protect implementation details.
  • Use readonly for values that should not change after construction.
  • Use implements to verify a class satisfies an interface.
  • Use abstract classes only when shared implementation is useful.
  • Explain the purpose of TypeScript in your own words.
  • Run or trace a small TypeScript example for TypeScript.
  • Test a normal case, a boundary case, and a broken case.
  • Verify the result with visible output, logs, metrics, compiler feedback, or a table.
  • Summarize the common mistake and the correction.
Common Mistakes to Avoid
WRONG Create classes for every plain data object.
RIGHT Use object types or interfaces for simple data shapes.
Classes are most useful when behavior matters.
WRONG Assume private exists at runtime in every style.
RIGHT Understand TypeScript private is mainly compile-time, while #private is JavaScript runtime private.
Choose the privacy style your project expects.
WRONG Learning TypeScript only as a term.
RIGHT Learn it through a working example, a boundary case, and a failure case.
Concept plus behavior is easier to remember than definition alone.
WRONG Skipping verification.
RIGHT Always check output, state, logs, metrics, query results, or compiler feedback.
Verification turns confidence into evidence.
WRONG Changing many things at once while debugging.
RIGHT Change one setting, input, or line, then inspect the result.
Small changes reveal the real cause.

Practice Tasks

  • Create a `BankAccount` class with private balance and deposit/withdraw methods.
  • Create an interface `Logger` and two classes that implement it.
  • Refactor repeated report export code into an abstract class.
  • Create a small demo that shows TypeScript clearly.
  • Add one edge case and write the expected result before running it.
  • Break the demo intentionally and document the error symptom.
  • Fix the broken version and explain why the fix works.

Frequently Asked Questions

They use JavaScript class runtime behavior, but TypeScript adds compile-time type checking, access modifiers, parameter properties, and abstract class checks.

Use functions for stateless behavior and classes when you need objects with encapsulated state and related methods.

Start with one tiny example, trace every step, then compare it with a broken version.

Verify the visible result: output, state, log entry, metric, query result, compiler feedback, or rendered behavior.

It often combines vocabulary with behavior. The confusion drops when you trace the input, rule, result, and failure path.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.