Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

Objects in TypeScript

Learn how to create objects, define property types, access and update properties, use optional and readonly properties, and work with nested objects and object methods.

Simple Explanation: An object stores related information using properties and values. For example, a student object can contain a name, age, course, and marks. TypeScript helps us define the expected type of each property.

What Is an Object?

An object is a collection of related properties. Each property has a name and a value. The value can be a string, number, boolean, array, another object, or even a function.

Objects are useful when we want to represent real-world entities such as students, employees, courses, products, and customer records.

  • Objects store information using property names.
  • Different properties can have different types.
  • Properties can be accessed and updated.
  • TypeScript can check an object's structure using type annotations.
  • Objects can contain nested objects and methods.

Object Workflow

Follow these steps to understand how an object is created and used in a TypeScript application.

📝
Step 1
Create Object

Define the object and its properties.

→
📦
Step 2
Store Values

Assign values to object properties.

→
🔍
Step 3
Access Properties

Read or update the stored information.

→
✅
Step 4
Use Object Data

Process and display the information.

Visual Example: Student Object
👨‍🎓
Student Object

Represents one student.

→
Name

Priya

Age

22

Course

TypeScript

Active

true

1. Creating an Object in TypeScript

We can create an object using curly braces. Inside the braces, we define properties and their corresponding values.

Syntax

let objectName = {
    property1: value1,
    property2: value2
};

Example

let student = {
    name: "Rahul",
    age: 22,
    course: "TypeScript"
};

console.log(student);

Expected Output

{
  name: 'Rahul',
  age: 22,
  course: 'TypeScript'
}

Explanation

  • name stores a string.
  • age stores a number.
  • course stores the course name.
  • Each property belongs to the student object.

2. Accessing Object Properties

We can access object properties using dot notation or bracket notation.

Example

let student = {
    name: "Priya",
    age: 22,
    course: "Java"
};

console.log(student.name);
console.log(student["age"]);
console.log(student.course);

Expected Output

Priya
22
Java

Explanation

  • student.name uses dot notation.
  • student["age"] uses bracket notation.
  • Both approaches access the corresponding property.

3. Updating Object Properties

We can update an existing property by assigning a new value to it, provided the new value matches its expected type.

Example

let student = {
    name: "Rahul",
    age: 21,
    course: "Java"
};

student.age = 22;
student.course = "TypeScript";

console.log(student);

Expected Output

{
  name: 'Rahul',
  age: 22,
  course: 'TypeScript'
}

Explanation

The age and course properties are updated. The name remains unchanged.

4. Adding and Removing Object Properties

JavaScript objects can have properties added or removed at runtime. However, TypeScript checks object shapes according to their declared types.

Example: Delete a Property

let student = {
    name: "Priya",
    age: 22,
    course: "Python"
};

delete student.course;

console.log(student);

Expected Output

{ name: 'Priya', age: 22 }

Adding a Property

type Student = {
    name: string;
    age: number;
    course?: string;
};

let student: Student = {
    name: "Amit",
    age: 23
};

student.course = "Java";

console.log(student);

Expected Output

{ name: 'Amit', age: 23, course: 'Java' }

The optional course property allows the object to be created without a course and assigned one later.

5. Defining Object Types

TypeScript allows us to describe an object's expected properties and their types using a type annotation.

Example

let student: {
    name: string;
    age: number;
    course: string;
} = {
    name: "Priya",
    age: 22,
    course: "Dot Net Full Stack"
};

console.log(student.name);
console.log(student.age);
console.log(student.course);

Expected Output

Priya
22
Dot Net Full Stack

Explanation

  • name must be a string.
  • age must be a number.
  • course must be a string.
Remember: When using this object type, the required properties must be supplied and their values must match the declared types.

6. Using Type Aliases for Objects

When multiple objects share the same structure, a type alias lets us define that structure once and reuse it.

Example

type Student = {
    name: string;
    age: number;
    course: string;
};

let student1: Student = {
    name: "Rahul",
    age: 22,
    course: "Java"
};

let student2: Student = {
    name: "Priya",
    age: 21,
    course: "Python"
};

console.log(student1.name);
console.log(student2.name);

Expected Output

Rahul
Priya

Explanation

The Student type alias describes the structure shared by both objects. Each object must provide the required properties with their declared types.

7. Optional Object Properties

Use the question mark symbol after a property name to make that property optional.

Example

type Student = {
    name: string;
    age: number;
    course?: string;
};

let student1: Student = {
    name: "Rahul",
    age: 22
};

let student2: Student = {
    name: "Priya",
    age: 21,
    course: "TypeScript"
};

console.log(student1);
console.log(student2);

Expected Output

{ name: 'Rahul', age: 22 }
{ name: 'Priya', age: 21, course: 'TypeScript' }

Explanation

The course property is optional. The first object can omit it, while the second object includes it.

8. Readonly Object Properties

The readonly modifier prevents a property from being reassigned through a reference with that readonly type.

Example

type Employee = {
    readonly id: number;
    name: string;
};

let employee: Employee = {
    id: 101,
    name: "Amit"
};

employee.name = "Rahul";

console.log(employee.id);
console.log(employee.name);

Expected Output

101
Rahul

Invalid Operation

// TypeScript compile-time error:
employee.id = 102;
Remember: Readonly prevents reassignment through the typed reference at compile time. It does not automatically freeze the entire object at runtime.

9. Nested Objects in TypeScript

An object can contain another object as a property. This is called a nested object and helps organize related information into groups.

Example

type Student = {
    name: string;
    address: {
        city: string;
        pinCode: number;
    };
};

let student: Student = {
    name: "Priya",
    address: {
        city: "Pune",
        pinCode: 411028
    }
};

console.log("Name:", student.name);
console.log("City:", student.address.city);
console.log("PIN Code:", student.address.pinCode);

Expected Output

Name: Priya
City: Pune
PIN Code: 411028

Explanation

  • The student object contains a name property.
  • The address property contains another object.
  • Nested properties are accessed using chained dot notation.

10. Methods Inside Objects

An object can contain methods. A method is a function stored as an object property and can work with the object's data.

Example

let student = {
    name: "Rahul",
    course: "TypeScript",

    displayDetails(): void {
        console.log("Name:", this.name);
        console.log("Course:", this.course);
    }
};

student.displayDetails();

Expected Output

Name: Rahul
Course: TypeScript

Explanation

  • displayDetails() is a method of the object.
  • The this keyword refers to the object when the method is called as shown.
  • The method displays values from the same object.

11. Objects vs Arrays

Objects and arrays both store information, but they organize and access it differently.

Feature Object Array
Stores Named properties and values. Ordered collection of elements.
Access Property names. Numeric indexes.
Example student.name courses[0]
Typical use Represent a student or employee. Store a list of students or courses.
Type definition Can specify different property types. Can specify element types for the collection.

12. Practical Example: CIIT Student Details

Let's define a reusable Student type and create an object containing a student's details.

Example

type Student = {
    id: number;
    name: string;
    course: string;
    marks: number;
    isActive: boolean;
};

let student: Student = {
    id: 101,
    name: "Priya",
    course: "Dot Net Full Stack",
    marks: 88,
    isActive: true
};

console.log("Student ID:", student.id);
console.log("Name:", student.name);
console.log("Course:", student.course);
console.log("Marks:", student.marks);
console.log("Active:", student.isActive);

Expected Output

Student ID: 101
Name: Priya
Course: Dot Net Full Stack
Marks: 88
Active: true

Explanation

  • The Student type describes the required properties.
  • The object stores the details of one student.
  • Each property is checked against its declared type.
  • The properties are accessed with dot notation.

Common Mistakes

  • Accessing a property using an incorrect property name.
  • Assigning a value that does not match the declared property type.
  • Forgetting required properties when creating an explicitly typed object.
  • Updating a readonly property.
  • Accessing nested properties using the wrong path.
  • Assuming that readonly automatically freezes an entire object at runtime.
Remember: Define the expected structure of an object clearly. Use optional properties when a property may be absent, and use readonly when reassignment should be prevented through the typed reference.

Practice Task

Write TypeScript programs to complete the following tasks.

  • Create an employee object containing ID, name, designation, and salary.
  • Access and update the properties of an object.
  • Define a Product type using a type alias.
  • Create an object with an optional email property.
  • Create a readonly property and identify the assignment that TypeScript rejects.
  • Create a nested object containing student details and address information.
  • Add a method to an object that displays its details.
Challenge: Create an array of Student objects and display each student's name and course.

Summary

In this lesson, we learned how to create objects, access and update their properties, define object types using type aliases, use optional and readonly properties, and work with nested objects and methods. Objects help organize related information into a clear structure.