Classes in TypeScript
Course contents (16 lessons)
- Getting started
- Why TypeScript? What it is and what it is not
- Setting up TypeScript: tsc and tsconfig.json
- Core types
- Basic types: primitives, arrays, tuples, any and unknown
- Typing functions: parameters, returns, optionals and overloads
- Objects, interfaces and type aliases
- Unions, literals and enums
- Union types and type narrowing
- Literal types, enums and as const
- Classes and generics
- Classes in TypeScript
- Generics: writing reusable typed code
- Built-in utility types: Partial, Pick, Omit, Record and more
- Advanced types
- Mapped and conditional types
- Modules, type imports and declaration files
- TypeScript in real projects
- Typing async code and API responses
- Strict mode and compiler flags that matter
- Migrating a JavaScript project to TypeScript
- Final project: a type-safe task manager
Classes you already know, with types
If you know JavaScript classes, TypeScript adds three things: types for properties, access modifiers, and implements and abstract for contracts.
class BankAccount {
readonly owner: string;
private balance: number;
constructor(owner: string, initialBalance: number = 0) {
this.owner = owner;
this.balance = initialBalance;
}
deposit(amount: number): void {
if (amount <= 0) throw new Error("Amount must be positive");
this.balance += amount;
}
getBalance(): number {
return this.balance;
}
}
const account = new BankAccount("Ali", 1000);
account.deposit(500);
console.log(account.owner, account.getBalance()); // Ali 1500
// account.balance = 0; // Error: 'balance' is private
// account.owner = "Bilal"; // Error: read-only
Properties must be declared in the class body with a type. Under strict, a property with no initial value must be set in the constructor, or the compiler complains that it is "not definitely assigned".
Access modifiers
| Modifier | Visible to |
|---|---|
public (the default) | Everyone |
protected | The class and its subclasses |
private | The class only |
readonly | Everyone can read, only the constructor can set |
private in TypeScript is a compile-time check. At runtime, the property is a normal one that any JavaScript code can read. If you need real runtime privacy, use JavaScript's #name private fields, which TypeScript supports as well:
class Counter {
#count = 0;
increment(): number {
return ++this.#count;
}
}
const c = new Counter();
c.increment();
console.log(c.increment()); // 2
Parameter properties
A common pattern is to receive constructor parameters and copy them into properties. TypeScript has a shortcut. Put a modifier in front of the parameter, and it is declared and assigned for you:
class Product {
constructor(
public readonly id: number,
public name: string,
private cost: number,
) {}
margin(price: number): number {
return price - this.cost;
}
}
const p = new Product(1, "Keyboard", 2500);
console.log(p.name, p.margin(3500)); // Keyboard 1000
That is the whole class. Some teams like the shortness, others find it hides what the class has. Be consistent with your team. Note that parameter properties are one of the TypeScript features that need a real compiler. Pure type stripping cannot handle them.
Implementing interfaces
A class can promise to follow an interface with implements. The compiler checks that it does:
interface Printable {
print(): string;
}
class Invoice implements Printable {
constructor(private total: number) {}
print(): string {
return `Invoice total: Rs. ${this.total}`;
}
}
class Receipt implements Printable {
print(): string {
return "Thank you for your purchase";
}
}
const docs: Printable[] = [new Invoice(2500), new Receipt()];
for (const doc of docs) {
console.log(doc.print());
}
The array holds different classes, and our code only depends on the interface. That makes it easy to add a new kind of document later. Remember that implements only checks; it does not copy any code into the class.
Inheritance and abstract classes
abstract class Shape {
constructor(public readonly name: string) {}
abstract area(): number; // subclasses must implement this
describe(): string {
return `${this.name} with area ${this.area().toFixed(2)}`;
}
}
class Circle extends Shape {
constructor(private radius: number) {
super("Circle");
}
area(): number {
return Math.PI * this.radius ** 2;
}
}
class Rectangle extends Shape {
constructor(private width: number, private height: number) {
super("Rectangle");
}
override area(): number {
return this.width * this.height;
}
}
// const s = new Shape("x"); // Error: cannot create an instance of an abstract class
console.log(new Circle(1).describe());
console.log(new Rectangle(2, 3).describe());
An abstract class is a partial base class that cannot be created directly. It can mix finished methods like describe with abstract ones that children must supply. The override keyword is optional, but it asks the compiler to confirm that the parent really has that method, which catches typos. Turn on the noImplicitOverride option to require it.
Static members and getters
class IdGenerator {
private static next = 1;
static create(): number {
return IdGenerator.next++;
}
}
class Temperature {
constructor(private celsius: number) {}
get fahrenheit(): number {
return this.celsius * 9 / 5 + 32;
}
}
console.log(IdGenerator.create(), IdGenerator.create()); // 1 2
console.log(new Temperature(100).fahrenheit); // 212
Structural typing applies to classes too
Two classes with the same public shape are interchangeable in TypeScript. Private and protected members change that. Only the original class satisfies a type that has private members. This is why a type with private fields behaves like a "nominal" type.
Composition over inheritance
The same advice as in JavaScript. Deep class trees are brittle. For many cases, a plain function or a small object that you pass in is simpler than a base class. A class is a good fit when you have state that goes with behaviour, such as an account, a connection or a cache.
Common mistakes
- **Treating
privateas security.** It disappears at runtime. Use#privatewhen it matters. - **Forgetting
super()first in a subclass constructor.** The compiler will tell you. - Uninitialised properties. Strict mode flags them. Initialise them, make them optional, or assign in the constructor.
- **Passing a method as a callback and losing
this.** Same problem as in JavaScript. Use an arrow function or an arrow property. - Inheriting for code reuse only. Prefer composition.
Try it yourself
- Write a
Stack<T>-like class for numbers withpush,popand a read-onlysizegetter, using a private array. - Create an interface
Loggerwithlog(message: string): void, and two classes that implement it. - Turn
Shapeinto an abstract class with a third subclassTriangle. - Convert the
Productexample to use#costinstead of a TypeScriptprivatemodifier, and note what else must change.
class BankAccount {
readonly owner: string;
private balance: number;
constructor(owner: string, initialBalance: number = 0) {
this.owner = owner;
this.balance = initialBalance;
}
deposit(amount: number): void {
if (amount <= 0) throw new Error("Amount must be positive");
this.balance += amount;
}
getBalance(): number {
return this.balance;
}
}
const account = new BankAccount("Ali", 1000);
account.deposit(500);
console.log(account.owner, account.getBalance()); // Ali 1500
// account.balance = 0; // Error: 'balance' is private
// account.owner = "Bilal"; // Error: read-only
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account