In TypeScript, an Object is a collection of properties (key-value pairs).
Each property has:
- A property name (key).
- A property value.
- A data type.
For example, in a Student Management System, a student can have a name, age, email, address, and admission status.
Here, student is an object.
1. What is an Object?
Consider these individual variables:
The problem is that all student information is stored in separate variables.
Instead, we can group related information into one object.
2. Object Type Annotation
In TypeScript, you can explicitly define the structure of an object.
Syntax:
Example:
3. Accessing Object Properties
There are two common ways to access object properties.
A. Dot Notation
Output:
B. Bracket Notation
Output:
5. Optional Properties
Sometimes an object doesn't need to contain every property.
For example, a student may or may not have a phone number.
TypeScript provides ? for optional properties.
6. Readonly Properties
Sometimes you want a property to be assigned once and then prevent reassignment.
Use readonly.
You can read the ID:
But you cannot modify it:
7. Nested Objects
An object can contain another object as a property.
For example, a student may have an address.
Access nested properties:
8. Object Inside an Array
You can store multiple objects inside an array.
For example, you want to store 3 students.
Now you can loop through students:
9. Object as a Function Parameter
This is extremely useful in real applications.
Suppose you want to create a function that accepts student information.
Call the function:
10. Object as a Function Return Type
A function can also return an object.
Use it:
11. Type Alias for Objects
Now imagine you have 20 functions that work with student objects.
Writing the same object structure repeatedly is not a good approach.
TypeScript provides Type Aliases.
Now use it anywhere:
12. Interface for Objects
TypeScript also provides interface to define object structures.
Example:
Use it:
14. Index Signatures
Sometimes you don't know the property names in advance.
For example, suppose you want to store student marks for different subjects.
Here:
Means:
- Property names can be strings.
- Property values must be numbers.
You can add:
Another practical example: Dynamic settings
This is useful when working with dynamic object properties.
15. Object Destructuring
Destructuring allows you to extract properties from an object into separate variables.
16. Spread Operator with Objects
The spread operator (...) copies enumerable own properties from an object into another object.
A. Copying an object
B. Adding new properties
Result:
C. Updating existing properties
The new age overrides the old value.