TypeScript Objects

An object is a fundamental data structure representing a collection of key-value pairs, where keys are strings or symbols and values can be of any data type, including other objects. Objects are instances of classes or prototypes, and they enable the organization and manipulation of data in a structured manner.

TypeScript enhances the capabilities of objects by allowing the definition of their shape through interfaces, providing static typing for better code validation and editor support. Objects play a central role in building and modeling applications, facilitating the encapsulation of related data and functionality within a cohesive unit, contributing to the principles of modularity and abstraction in software development.

Object Creation using Classes

TypeScript allows the creation of objects using classes, providing a blueprint for object instances with predefined properties and methods.

class Person { firstName: string; lastName: string; constructor(firstName: string, lastName: string) { this.firstName = firstName; this.lastName = lastName; } getFullName(): string { return `${this.firstName} ${this.lastName}`; } } // Creating an object using the class const person1 = new Person("Emil", "Sparrow"); console.log(person1.getFullName()); // Output: Emil Sparrow

Here, person1 is an object created from the Person class, encapsulating the data (firstName, lastName) and behavior (getFullName()).

Plain JavaScript Object

TypeScript supports the creation of objects using plain JavaScript syntax, allowing flexibility without the need for class definitions.

// Creating an object using plain JavaScript syntax const car = { brand: "Toyota", model: "Camry", year: 2022, startEngine: function () { console.log("Engine started!"); }, }; console.log(car.brand); // Output: Toyota car.startEngine(); // Output: Engine started!

Here, car is a plain JavaScript object with properties (brand, model, year) and a method (startEngine).

Classes and Constructors

class Person { constructor(public name: string, private age: number) {} public getAge(): number { return this.age; } } const jane = new Person("Jane", 25); console.log(jane.name); // Outputs "Jane" // Cannot access private property directly: console.log(jane.age); // Error console.log(jane.getAge()); // Outputs 25 using public method

This example uses a class and constructor to define objects with typed properties and access control. Separating public and private data ensures controlled access and data integrity.

Inheritance and Polymorphism

class Employee extends Person { public salary: number; constructor(name: string, age: number, salary: number) { super(name, age); this.salary = salary; } public raiseSalary(amount: number): void { this.salary += amount; } } const employee = new Employee("John", 30, 50000); employee.raiseSalary(1000); console.log(employee.salary); // Outputs 51000 // Polymorphism: same method call, different behavior const manager = new Employee("Jane", 35, 60000); manager.raiseSalary(2000); console.log(manager.salary); // Outputs 62000

Here, inheritance shows Employee inheriting properties and methods from Person, adding specific ones like salary. Polymorphism demonstrates how the same raiseSalary method acts differently on different object types (employee vs. manager).

Destructuring and Generics

const product = { name: "Shirt", price: 20, color: "Blue" }; const { name, price } = product; // Destructure object into variables console.log(name); // Outputs "Shirt" console.log(price); // Outputs 20 class Basket<T> { items: T[] = []; addItem(item: T): void { this.items.push(item); } } const basket1 = new Basket<string>(); // Holds strings basket1.addItem("Apple"); const basket2 = new Basket<number>(); // Holds numbers basket2.addItem(10);

This example showcases destructuring for extracting specific properties and generics for creating objects that work with different data types at runtime.

Object Types and Interfaces

TypeScript allows developers to specify and enforce the types of object properties using interfaces.

interface Point { x: number; y: number; } // Creating an object with a specific type const point: Point = { x: 5, y: 10 }; console.log(point.x + point.y); // Output: 15

In this example, the Point interface defines the structure of an object with numeric properties x and y. The point object adheres to this type.

Advanced Features

  1. Decorators can enhance objects with additional functionalities at runtime.
  2. Interfaces define contracts for objects, specifying required properties and methods.
  3. Utility types like keyof and typeof offer advanced property access and manipulation.

Conclusion

Objects can be created either through class instances, encapsulating data and behavior, or as plain JavaScript objects. Developers can enforce property types using interfaces, and TypeScript supports features like object spread and destructuring for concise manipulation and creation of objects.