Classes
Define blueprints for objects with typed properties and a constructor.
Syntax
class Point { x: number; y: number; }TypeScript classes work like JavaScript classes but add types to properties and methods. Declare fields with their types, then initialize them in the constructor.
Creating instances
Use new ClassName(...) to build an object from the class.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- A User class encapsulates id, name, and email with a typed constructor to enforce data shape on instantiation.
- A BankAccount class holds a balance number with typed deposit and withdraw methods to model business logic.
- A Logger class stores a prefix string and exposes a typed log method reusable across the application.
More examples
Class with typed properties
Declares typed class properties, a typed constructor, and a method with a typed parameter and return value.
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
distanceTo(other: Point): number {
return Math.sqrt((this.x - other.x) ** 2 + (this.y - other.y) ** 2);
}
}Class used as a type
Instantiates a class and passes it to a function typed as User, demonstrating classes as structural types.
class User {
id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
function welcome(user: User): string {
return `Welcome, ${user.name}!`;
}
const alice = new User(1, 'Alice');
console.log(welcome(alice));Class with a method that mutates
Shows a class with a mutable property and two typed methods, one with a default parameter.
class Counter {
count: number = 0;
increment(by: number = 1): void {
this.count += by;
}
reset(): void {
this.count = 0;
}
}
const c = new Counter();
c.increment();
c.increment(5);
console.log(c.count); // 6
Discussion