Understanding TypeScript Classes: 20 Practical Examples

 

Introduction

TypeScript enhances JavaScript by adding strong typing and modern features. One of its key features is classes, which help structure code in an object-oriented manner. This blog will explore 20 examples of TypeScript classes, showcasing their syntax and functionality.

Example 1: Basic Class Definition

class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } }

Example 2: Creating an Instance


const person1 = new Person("Alice", 30); console.log(person1);

Example 3: Method in a Class


class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return `Hello, ${this.greeting}!`; } } const greeter = new Greeter("World"); console.log(greeter.greet());

Example 4: Class Inheritance


class Employee extends Person { position: string; constructor(name: string, age: number, position: string) { super(name, age); this.position = position; } } const employee = new Employee("Bob", 28, "Developer"); console.log(employee);

Example 5: Getter and Setter


class Circle { private radius: number; constructor(radius: number) { this.radius = radius; } get area() { return Math.PI * this.radius ** 2; } set radiusValue(value: number) { this.radius = value; } } const circle = new Circle(5); console.log(circle.area); circle.radiusValue = 10; console.log(circle.area);

Example 6: Static Methods


class MathUtils { static add(a: number, b: number) { return a + b; } } console.log(MathUtils.add(5, 10));

Example 7: Abstract Classes


abstract class Animal { abstract makeSound(): void; } class Dog extends Animal { makeSound() { console.log("Woof!"); } } const dog = new Dog(); dog.makeSound();

Example 8: Interfaces with Classes


interface Printable { print(): void; } class Document implements Printable { title: string; constructor(title: string) { this.title = title; } print() { console.log(`Document Title: ${this.title}`); } } const doc = new Document("My Document"); doc.print();

Example 9: Class with Optional Properties


class Car { make: string; model: string; year?: number; constructor(make: string, model: string, year?: number) { this.make = make; this.model = model; this.year = year; } } const myCar = new Car("Toyota", "Corolla"); console.log(myCar);

Example 10: Readonly Properties


class Point { readonly x: number; readonly y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } } const point = new Point(10, 20); // point.x = 15; // Error: Cannot assign to 'x' because it is a readonly property.

Example 11: Class with Default Parameters

class Rectangle { width: number; height: number; constructor(width: number = 5, height: number = 10) { this.width = width; this.height = height; } } const rectangle = new Rectangle(); console.log(rectangle);

Example 12: Private Properties


class BankAccount { private balance: number; constructor(initialBalance: number) { this.balance = initialBalance; } deposit(amount: number) { this.balance += amount; } getBalance() { return this.balance; } } const account = new BankAccount(100); account.deposit(50); console.log(account.getBalance());

Example 13: Method Overloading


class Calculator { add(a: number, b: number): number; add(a: string, b: string): string; add(a: any, b: any): any { return a + b; } } const calc = new Calculator(); console.log(calc.add(5, 10)); // 15 console.log(calc.add("Hello, ", "World!")); // Hello, World!

Example 14: Using this in Methods


class Counter { count: number; constructor() { this.count = 0; } increment() { this.count++; } getCount() { return this.count; } } const counter = new Counter(); counter.increment(); console.log(counter.getCount());

Example 15: Class Decorators


function LogClass(target: Function) { console.log(`Class ${target.name} was created.`); } @LogClass class User { constructor(public name: string) {} } const user = new User("Charlie");

Example 16: Parameter Decorators


function LogParameter(target: any, propertyKey: string, parameterIndex: number) { console.log(`Parameter in ${propertyKey} at index ${parameterIndex} was decorated.`); } class Order { constructor(public id: number, @LogParameter public product: string) {} } const order = new Order(1, "Laptop");

Example 17: Using Class Expressions


const Vehicle = class { constructor(public type: string) {} }; const bike = new Vehicle("Bicycle"); console.log(bike);

Example 18: Mixed Types in a Class


class MultiType { private values: (string | number)[]; constructor() { this.values = []; } addValue(value: string | number) { this.values.push(value); } getValues() { return this.values; } } const multiType = new MultiType(); multiType.addValue(42); multiType.addValue("Hello"); console.log(multiType.getValues());

Example 19: Implementing Multiple Interfaces


interface Movable { move(): void; } interface Stoppable { stop(): void; } class Car implements Movable, Stoppable { move() { console.log("Car is moving"); } stop() { console.log("Car has stopped"); } } const myCar2 = new Car(); myCar2.move(); myCar2.stop();

Example 20: Instance of Type


function isPerson(obj: any): obj is Person { return 'name' in obj && 'age' in obj; } const unknownObj = { name: "Eve", age: 25 }; if (isPerson(unknownObj)) { console.log(`${unknownObj.name} is a person.`); }

Conclusion

TypeScript classes offer a powerful way to structure applications while leveraging strong typing. The examples presented here illustrate various features and use cases. By adopting classes, developers can create more maintainable and organized code.

Comments

Popular Posts