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.
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.
Here, car is a plain JavaScript object with properties (brand, model, year) and a method (startEngine).
Classes and Constructors
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
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
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.
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
- Decorators can enhance objects with additional functionalities at runtime.
- Interfaces define contracts for objects, specifying required properties and methods.
- 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.