Difficulty: Intermediate
Classes in TypeScript provide a blueprint for creating objects with predefined properties and methods. They bring traditional object-oriented programming patterns to JavaScript while adding type safety through TypeScript's type system. A class encapsulates data (properties) and behavior (methods) into a single unit.
The constructor is a special method that runs when you create a new instance of a class using the `new` keyword. Inside the constructor, you typically initialize the object's properties. TypeScript requires you to declare property types either in the class body or via parameter properties, ensuring every instance has a well-defined shape.
Methods are functions defined inside a class that operate on the instance's data. They have access to `this`, which refers to the current instance. Unlike plain objects, classes let you define a reusable template: create as many instances as you need, and each one carries its own copy of the property values while sharing the same method definitions through the prototype chain.
TypeScript classes also support type annotations on properties, method parameters, and return types. This means the compiler can catch errors like assigning a string to a numeric property or calling a method with the wrong arguments, all at compile time rather than runtime.
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): string {
return `Hi, I'm ${this.name} and I'm ${this.age} years old.`;
}
}
const alice = new Person("Alice", 30);
console.log(alice.greet());
console.log(alice.name);
The Person class declares two properties with types, initializes them in the constructor, and exposes a greet method that returns a formatted string.
class Calculator {
private result: number;
constructor(initial: number = 0) {
this.result = initial;
}
add(value: number): Calculator {
this.result += value;
return this;
}
subtract(value: number): Calculator {
this.result -= value;
return this;
}
getResult(): number {
return this.result;
}
}
const calc = new Calculator(10);
console.log(calc.add(5).subtract(3).getResult());
This Calculator class demonstrates method chaining by returning `this` from each operation method, enabling a fluent API style.
class Config {
host: string;
port: number;
debug: boolean;
constructor(host: string, port: number = 3000, debug: boolean = false) {
this.host = host;
this.port = port;
this.debug = debug;
}
summary(): string {
return `${this.host}:${this.port} (debug=${this.debug})`;
}
}
const dev = new Config("localhost", 8080, true);
const prod = new Config("api.example.com");
console.log(dev.summary());
console.log(prod.summary());
Default parameter values in the constructor let you create instances without supplying every argument, while TypeScript still enforces types.
class declaration, constructor, methods, properties, instances