Skip to lesson

TypeScript · Lesson 31 of 42

Classes: properties, methods and access modifiers

Write TypeScript classes with typed properties, constructors, parameter properties, public, private and protected members, readonly, static and getters.

Beginner to advanced·16 min·Classes·Updated 2026-11-24

UNDERSTAND IT. THEN TRY IT.

What you can do after this lesson

You will write classes in TypeScript, with typed properties and methods, and control which code may touch what. Classes are plain JavaScript classes plus type information and a few extra keywords, so everything you know about JavaScript classes still applies.

Declaring properties

A class lists its properties with types, usually at the top, and assigns them in the constructor:

typescript
class Product {
  name: string;
  price: number;

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

  describe(): string {
    return `${this.name} costs ${this.price.toFixed(2)}`;
  }
}

const pen = new Product("Pen", 2.5);
console.log(pen.describe());
result
Pen costs 2.50

In strict mode, the compiler also checks that every property is initialised. If you declare a property and forget to assign it, you get an error, because the property would be undefined when read:

typescript
class Product {
  name: string;
  price: number;

  constructor(name: string) {
    this.name = name;
  }
}
result
example.ts(3,3): error TS2564: Property 'price' has no initializer and is not definitely assigned in the constructor.

Fix it by assigning in the constructor, giving the property an initial value, or making it optional (price?: number). Do not reach for the definite assignment assertion (price!: number) unless something else, such as a framework, really does assign the property later.

Parameter properties

The constructor above repeats each name three times. TypeScript has a shortcut: put an access modifier in front of a constructor parameter and it becomes a property, assigned automatically:

typescript
class Product {
  constructor(
    public name: string,
    public price: number,
  ) {}

  describe(): string {
    return `${this.name} costs ${this.price.toFixed(2)}`;
  }
}

console.log(new Product("Pen", 2.5).describe());
result
Pen costs 2.50

The two classes are equivalent. Parameter properties are a TypeScript feature that creates code in the output, which matters if you use the erasableSyntaxOnly option from the enums lesson.

Access modifiers

Three keywords control access, and they are checked by the compiler:

  • public (the default): usable anywhere.
  • private: usable only inside the class.
  • protected: usable inside the class and its subclasses.
typescript
class Account {
  private balance = 0;

  deposit(amount: number): void {
    this.balance += amount;
  }

  get total(): number {
    return this.balance;
  }
}

const account = new Account();
account.deposit(100);
console.log(account.total);
console.log(account.balance);
result
example.ts(16,21): error TS2341: Property 'balance' is private and only accessible within class 'Account'.

The class exposes deposit and a read-only view, total, while keeping the raw balance hidden. This is called encapsulation: outside code can only use the safe operations you chose to offer.

There is a catch you must understand. TypeScript's private exists only at compile time. In the JavaScript that runs, the property is an ordinary one, and anyone can reach it, for example by bypassing the checker:

typescript
class Safe {
  private secret = "tsPrivate";
  #hidden = "jsPrivate";
}

const safe = new Safe();
console.log((safe as any).secret, (safe as any).hidden);
result
tsPrivate undefined

The private member was readable, because the checker was bypassed. The #hidden member, a JavaScript private field written with a hash, was not. A #field is enforced by the JavaScript engine itself, so it is the right choice when you need real privacy at run time. Use private when compile-time protection against mistakes is enough.

readonly and static

readonly stops a property being changed after the constructor finishes. static members belong to the class itself, not to its instances:

typescript
class Counter {
  static created = 0;
  readonly id: number;

  constructor() {
    Counter.created++;
    this.id = Counter.created;
  }
}

const a = new Counter();
const b = new Counter();
console.log(a.id, b.id, Counter.created);
result
1 2 2

Changing a.id later would be a compile error, since it is read-only.

Getters and setters

Accessors behave like properties but run code. A getter with no setter is a neat way to expose a read-only computed value:

typescript
class Temperature {
  private celsius = 0;

  get fahrenheit(): number {
    return this.celsius * 9 / 5 + 32;
  }

  set fahrenheit(value: number) {
    this.celsius = (value - 32) * 5 / 9;
  }
}

const t = new Temperature();
t.fahrenheit = 212;
console.log(t.fahrenheit);
result
212

Classes as types

A class defines both a value (the constructor) and a type for its instances. You can annotate with the class name:

typescript
class Point {
  constructor(public x: number, public y: number) {}
}

function show(p: Point): string {
  return `(${p.x}, ${p.y})`;
}

console.log(show(new Point(1, 2)));
console.log(show({ x: 3, y: 4 }));
result
(1, 2)
(3, 4)

The second call may surprise you: a plain object is accepted, because TypeScript compares shape, not origin. This is called structural typing, and it holds for classes with only public members. A class with private or protected members is different, since only instances created by that class (or a subclass) fit.

Common mistakes

Assuming private is secure. It is a compile-time convenience. Use #field or keep secrets out of objects.

Forgetting to initialise properties. Strict mode catches it. Assign in the constructor or give a default.

Overusing classes. Plain objects and functions are often simpler. Use classes when you need instances with shared methods and state.

Using static for instance state. A static property is shared by every instance.

Exercise

Write a BankAccount class with a private balance, deposit and withdraw methods that refuse to go below zero by returning false, and a getter balance. Use a parameter property for the owner name. Try reading the private field from outside to see the error, and then write a second version that uses a #balance field.

Next: Abstract classes, inheritance and implementing interfaces.

KNOWLEDGE CHECK

A quick check. You’ve got this.

Try each question. Every answer comes with an explanation.

0 / 4 understood
01 What does strict property initialization require?
02 What does constructor(private name: string) do?
03 Which keeps a member truly private at run time in the emitted JavaScript?
04 Where can a protected member be used?

Ready for the next small win?

Mark the lesson complete when you are ready.

Course navigation

Frontend

TypeScript tutorial

Add types to JavaScript to catch mistakes before your code runs, from your first annotation to generics and real projects.

Your progress 0/42
Learning something new?Explore all courses