On this page

TypeScript Classes: Complete Guide

Published on August 3, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

TypeScript classes are a powerful way to structure code using object-oriented programming principles. They build on JavaScript's ES6 class syntax while adding type annotations, access modifiers, and other features that make your code safer and more predictable. With TypeScript, you can define exactly what properties and methods a class should have, control who can access them, and create reusable blueprints for objects. A class serves as a template for creating objects that share the same structure and behavior — for example, a User class might define properties like name and email, along with methods like sendMessage(). When you create a new instance of a class using the new keyword, you get an object that follows that blueprint, with all the type safety TypeScript provides. This guide covers everything from the basics of class members to advanced features like abstract classes, with plenty of practical examples to help you get started.


What Are Classes in TypeScript?​

A class is a blueprint for creating objects. It defines what properties an object will have and what methods it can perform. TypeScript classes are essentially an extension of JavaScript ES6 classes, enhanced with type annotations, access modifiers (public, private, protected), readonly fields, static members, and parameter properties. The syntax looks familiar to anyone who has used C#, Java, or modern JavaScript.

Here is the simplest class you can write in TypeScript:


class Point {

    x: number;

    y: number;

}



const pt = new Point();

pt.x = 0;

pt.y = 0;

The Point class defines two fields — x and y — both of type number. The new keyword creates an instance of the class, and then you can assign values to its properties. If you don't specify a type for a field, TypeScript will infer it as any, which is generally not recommended.

Adding an Initializer​

Fields can also have initial values that are set automatically when the class is instantiated:


class Point {

    x = 0;

    y = 0;

}



const pt = new Point();

console.log(`${pt.x}, ${pt.y}`); // Prints "0, 0"

TypeScript uses the initializer to infer the field's type, so you don't always need to write an explicit type annotation.


Class Members: Fields, Constructors, and Methods​

A class typically consists of three kinds of members: fields (properties), a constructor, and methods.

Fields​

Fields are the data that each instance of the class will hold. They can be typed explicitly or inferred from an initializer.


class Greeter {

    greeting: string; // Field



    constructor(message: string) {

        this.greeting = message;

    }



    greet() {

        return "Hello, " + this.greeting;

    }

}



const greeter = new Greeter("world");

console.log(greeter.greet()); // "Hello, world"

In this example, greeting is a field of type string. The constructor initializes it when a new instance is created, and the greet method returns a message using that field.

The Constructor​

The constructor is a special method that runs when you create a new instance of a class with new. It initializes the object's state. In TypeScript, constructor parameters can also have types, just like function parameters:


class User {

    name: string;

    age: number;



    constructor(name: string, age: number) {

        this.name = name;

        this.age = age;

    }

}



const user = new User("Alice", 30);

Methods​

Methods are functions that belong to a class. They can access the instance's properties using the this keyword:


class Calculator {

    add(a: number, b: number): number {

        return a + b;

    }



    subtract(a: number, b: number): number {

        return a - b;

    }

}



const calc = new Calculator();

console.log(calc.add(5, 3)); // 8

Methods can have type annotations for their parameters and return values, just like standalone functions.


Access Modifiers: Public, Private, and Protected​

TypeScript adds three access modifiers to control who can access class members:

These modifiers exist only at compile time. After TypeScript is compiled to JavaScript, they disappear, so runtime access is not restricted. They are a development tool that helps you write cleaner, more maintainable code.

Public (Default)​

If you don't specify a modifier, the member is public by default:


class User {

    public name: string; // 'public' is optional here



    constructor(name: string) {

        this.name = name;

    }

}



const user = new User("Alice");

console.log(user.name); // Works — 'name' is public

Private​

The private modifier restricts access to the class itself. Subclasses and external code cannot access private members:


class BankAccount {

    private balance: number = 0;



    deposit(amount: number) {

        this.balance += amount;

    }

}



const account = new BankAccount();

account.deposit(100);

console.log(account.balance); // ❌ Error: Property 'balance' is private

This enforces encapsulation and prevents accidental misuse of internal data.

Protected​

The protected modifier is similar to private, but it also allows access from subclasses:


class Animal {

    protected move() {

        console.log("Moving...");

    }

}



class Dog extends Animal {

    bark() {

        this.move(); // ✅ OK — 'move' is protected

        console.log("Woof!");

    }

}



const dog = new Dog();

dog.bark(); // âś… Works

dog.move(); // ❌ Error: Property 'move' is protected

This is useful for template methods and shared logic in inheritance hierarchies.


Parameter Properties: Shorter Constructor Syntax​

Writing class fields and then initializing them in the constructor can be repetitive:


class User {

    name: string;

    age: number;



    constructor(name: string, age: number) {

        this.name = name;

        this.age = age;

    }

}

TypeScript provides a shorthand called parameter properties. By adding an access modifier (or readonly) to a constructor parameter, TypeScript automatically declares a field with the same name and assigns the parameter's value to it:


class User {

    constructor(public name: string, public age: number) {}

}



const user = new User("Alice", 30);

console.log(user.name); // "Alice"

This single line declares both name and age as public fields, assigns them from the constructor arguments, and eliminates the boilerplate. You can use public, private, protected, and readonly with parameter properties.

Example with Readonly​


class Point {

    constructor(public readonly x: number, public readonly y: number) {}

}



const p = new Point(10, 20);

p.x = 5; // ❌ Error: Cannot assign to 'x' because it is a read-only property

Readonly Fields​

The readonly modifier prevents a field from being changed after it is initialized. Readonly fields can only be set at declaration or inside the constructor:


class Config {

    readonly version: string = "1.0.0";



    constructor() {

        // Can also be set here

        // this.version = "2.0.0";

    }

}



const config = new Config();

config.version = "2.0.0"; // ❌ Error: Cannot assign to 'version' because it is read-only

This is useful for values that should never change after the object is created, such as configuration settings or unique identifiers.


Inheritance with extends​

Classes can inherit from other classes using the extends keyword. The subclass (child class) gets all the properties and methods of the parent class and can add its own or override existing ones:


class Animal {

    move(distance: number = 0) {

        console.log(`Animal moved ${distance}m.`);

    }

}



class Dog extends Animal {

    bark() {

        console.log("Woof! Woof!");

    }

}



const dog = new Dog();

dog.bark();  // "Woof! Woof!"

dog.move(10); // "Animal moved 10m."

The Dog class inherits the move method from Animal and adds its own bark method. This promotes code reuse and establishes an "is-a" relationship between classes.

Super Keyword​

When you override a method in a subclass, you can call the parent class's version using super:


class Animal {

    speak() {

        console.log("Animal speaks");

    }

}



class Dog extends Animal {

    speak() {

        super.speak(); // Calls Animal's speak method

        console.log("Dog barks");

    }

}



const dog = new Dog();

dog.speak();

// Output:

// "Animal speaks"

// "Dog barks"

The super keyword is also used to call the parent class's constructor from a subclass constructor.


Abstract Classes​

An abstract class is a class that cannot be instantiated directly. It is designed to be extended by other classes. Abstract classes can contain abstract methods — methods that have no implementation and must be provided by subclasses.


abstract class Shape {

    abstract area(): number;



    describe() {

        return `Area: ${this.area()}`;

    }

}



class Circle extends Shape {

    constructor(public radius: number) {

        super();

    }



    area(): number {

        return Math.PI * this.radius ** 2;

    }

}



const circle = new Circle(10);

console.log(circle.describe()); // "Area: 314.159..."

The Shape class cannot be instantiated directly:


new Shape(); // ❌ Error: Cannot create an instance of an abstract class

Abstract classes are ideal for defining a common interface and shared logic for a family of related classes, while leaving specific details to be implemented by subclasses.


Classes and Interfaces​

Classes can implement one or more interfaces using the implements keyword. This ensures the class provides all the properties and methods defined in the interface:


interface Serializable {

    serialize(): string;

}



class User implements Serializable {

    constructor(public name: string) {}



    serialize(): string {

        return JSON.stringify({ name: this.name });

    }

}



const user = new User("Alice");

console.log(user.serialize()); // '{"name":"Alice"}'

Unlike inheritance, a class can implement multiple interfaces, making it flexible for defining contracts:


interface Identifiable {

    id: string;

}



interface Timestamped {

    createdAt: Date;

}



class Document implements Identifiable, Timestamped {

    id: string;

    createdAt: Date;



    constructor(id: string) {

        this.id = id;

        this.createdAt = new Date();

    }

}

Static Members​

Static members belong to the class itself, not to instances of the class. They are accessed using the class name:


class MathUtils {

    static PI: number = 3.14159;



    static square(x: number): number {

        return x * x;

    }

}



console.log(MathUtils.PI); // 3.14159

console.log(MathUtils.square(5)); // 25

Static members are useful for utility functions and constants that don't depend on instance state.


Putting It All Together​

Here is a realistic example that combines multiple concepts — access modifiers, parameter properties, inheritance, and abstract classes:


abstract class Repository<T> {

    protected items: T[] = [];



    add(item: T) {

        this.items.push(item);

    }



    abstract findById(id: string): T | undefined;

}



interface Entity {

    id: string;

    name: string;

}



class UserRepository extends Repository<Entity> {

    findById(id: string): Entity | undefined {

        return this.items.find((item) => item.id === id);

    }

}



const repo = new UserRepository();

repo.add({ id: "1", name: "Alice" });

console.log(repo.findById("1")); // { id: "1", name: "Alice" }

This example demonstrates:


When to Use Classes vs. Interfaces​

A common question is when to use a class versus an interface. Interfaces are a compile‑time construct that describe the shape of an object. They disappear after compilation and have no runtime behavior. Classes, on the other hand, provide both a type and an implementation, and they exist at runtime.

Use interfaces when you only need to describe the shape of an object, such as for API responses, configuration objects, or function parameters. Use classes when you need to create objects with behavior, maintain state, or use inheritance.

You can also use a class and an interface together — the class implements the interface to ensure it satisfies the contract, while providing the actual implementation.


Summary​

TypeScript classes bring structure, safety, and clarity to JavaScript's class syntax. Here's what you've learned:

These features make TypeScript's class system far more expressive and safer than plain JavaScript, while staying fully compatible with JavaScript's runtime model. Whether you're building a small application or a large enterprise system, TypeScript classes give you the tools to write clean, maintainable, and type‑safe code.

Frequently Asked Questions on TypeScript Classes​

What are classes in TypeScript and why would I use them?

Classes in TypeScript are blueprints for creating objects with defined properties and methods. They build on JavaScript's ES6 class syntax while adding type annotations, access modifiers, and other features that make your code safer and more predictable. Use classes when you need to create multiple objects with the same structure and behavior, such as user accounts, database records, or UI components.

What are the three access modifiers in TypeScript classes?

TypeScript provides three access modifiers: `public` (accessible anywhere, this is the default), `private` (accessible only inside the class), and `protected` (accessible inside the class and its subclasses). These modifiers exist only at compile time and help you control visibility and enforce encapsulation.

What are parameter properties and how do I use them?

Parameter properties are a TypeScript shorthand that lets you declare and initialize class fields directly in the constructor. By adding an access modifier like `public`, `private`, `protected`, or `readonly` to a constructor parameter, TypeScript automatically declares a field with the same name and assigns the parameter value to it. Example: `constructor(public name: string, private age: number) {}`.

What is the difference between `private` and `protected` access modifiers?

`private` members are accessible only inside the class where they are declared. `protected` members are accessible inside the class and also inside any subclasses that extend the class. Neither is accessible from outside the class or its subclasses.

Can I use `readonly` with class fields?

Yes. The `readonly` modifier prevents a field from being changed after it is initialized. Readonly fields can only be set at declaration or inside the constructor. Attempting to change a `readonly` field elsewhere will result in a compile-time error.

Can a class implement multiple interfaces in TypeScript?

Yes, a class can implement multiple interfaces by listing them after the `implements` keyword, separated by commas. For example: `class User implements Identifiable, Serializable { ... }`. The class must provide implementations for all members of every interface it implements.

What is an abstract class and how is it different from an interface?

An abstract class is a class that cannot be instantiated directly. It is designed to be extended by other classes. Abstract classes can contain abstract methods (with no implementation) that subclasses must provide. An interface only defines the shape of an object without any implementation, while an abstract class can provide both partial implementation and a contract for subclasses.

Can a class extend another class and implement interfaces at the same time?

Yes. A class can extend one base class using `extends` and also implement one or more interfaces using `implements`. For example: `class PremiumUser extends User implements Serializable, Auditable { ... }`. The class inherits all members from the base class and must implement all members of the interfaces.

What are static members in TypeScript classes?

Static members belong to the class itself rather than to instances of the class. They are accessed using the class name, not an instance. Static members are useful for utility functions and constants that don't depend on instance state. Example: `class MathUtils { static PI = 3.14159; }`.

Why can't I access a private property from outside the class?

Private properties are intentionally restricted to the class they are declared in to enforce encapsulation — a core principle of object-oriented programming. This prevents external code from directly modifying internal state, which reduces bugs and makes the code easier to maintain. The restriction is enforced at compile time by TypeScript.

Are TypeScript access modifiers enforced at runtime?

No. Access modifiers like `public`, `private`, and `protected` are only enforced at compile time by TypeScript. When the code is compiled to JavaScript, these modifiers are removed, and there is no runtime enforcement. They are a development tool to help you write cleaner, more maintainable code.

When should I use a class versus an interface in TypeScript?

Use an interface when you only need to describe the shape of an object — for example, API responses, configuration objects, or function parameters. Interfaces are compile-time only and have no runtime behavior. Use a class when you need to create objects with behavior (methods), maintain state, or use inheritance. Classes provide both a type and an implementation.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Interfaces

Next

Implementing Interfaces