Typed Classes
TypeScript classes add typed fields plus access keywords like public, private and readonly.
What you will learn
- Type class fields and the constructor
- Control access with public and private
- Protect fields with readonly
A class with typed fields
You know JavaScript classes. TypeScript adds types to the fields and to the constructor, so an object built from the class always has the right shape.
class Student {
name: string;
grade: number;
constructor(name: string, grade: number) {
this.name = name;
this.grade = grade;
}
describe(): string {
return this.name + ' scored ' + this.grade;
}
}
const s = new Student('Asha', 92);
console.log(s.describe());Note: Output:
Asha scored 92
The fields name and grade are typed, the constructor requires matching arguments, and describe() is declared to return a string.
public vs private
Access keywords say who may touch a field. public (the default) means anyone; private means "only inside this class". Private fields stop outside code from poking at internals.
class BankAccount {
private balance: number;
constructor(start: number) {
this.balance = start;
}
deposit(amount: number): void {
this.balance += amount;
}
getBalance(): number {
return this.balance;
}
}
const acc = new BankAccount(100);
acc.deposit(50);
console.log(acc.getBalance());
console.log(acc.balance); // error — balance is privateNote: Output:
150
Error: Property 'balance' is private and only accessible within class 'BankAccount'.
You can deposit and read the balance through methods, but acc.balance directly is blocked — the class controls its own data.
readonly fields
Just like in interfaces, a class field can be readonly — set in the constructor, then locked.
class User {
readonly id: number;
name: string;
constructor(id: number, name: string) {
this.id = id; // ok — set in constructor
this.name = name;
}
}
const u = new User(1, 'Asha');
u.name = 'Asha S.'; // ok
u.id = 2; // error — id is readonlyNote: Output:
Error: Cannot assign to 'id' because it is a read-only property.
name can change, but id is fixed once the object is built — a common, safe pattern for identifiers.
| Keyword | Means |
|---|---|
public | Accessible anywhere (the default) |
private | Only inside this class |
readonly | Set once, then cannot change |
protected | Inside this class and its subclasses |
Tip: TypeScript has a shortcut: put an access keyword on a constructor parameter (constructor(private balance: number)) and it creates and assigns the field for you — less boilerplate.
Q. What does marking a class field private achieve?
✍️ Practice
- Write a
Timerclass with a privatesecondsfield and publictick()andgetTime()methods. - Add a
readonly createdAt: stringfield set in the constructor and try changing it afterwards.
🏠 Homework
- Build a
Counterclass with a private count, methods to increment and read it, and show the output of a few calls.