You are currently viewing TypeScript Objects: A Comprehensive Tutorial with Code Examples

TypeScript Objects: A Comprehensive Tutorial with Code Examples

In TypeScript, objects are a fundamental data type used to store collections of key-value pairs. They allow developers to organize and manipulate data in a structured manner. This tutorial will cover the basics of working with objects in TypeScript, including object creation, accessing properties, adding methods, and more.

Creating Objects in TypeScript

To create an object in TypeScript, you can use object literal notation. Here’s an example:

// Object with properties
let person = {
    name: "John",
    age: 30,
    city: "New York"
};

Accessing Object Properties

You can access object properties using dot notation or bracket notation:

// Dot notation
console.log(person.name); // Output: John

// Bracket notation
console.log(person['age']); // Output: 30

Adding Methods to Objects

Objects in TypeScript can also have methods:

let person = {
    name: "John",
    age: 30,
    city: "New York",
    greet: function() {
        console.log(`Hello, my name is ${this.name}.`);
    }
};

person.greet(); // Output: Hello, my name is John.

Object Types

You can define the structure of an object using interfaces or types:

interface Person {
    name: string;
    age: number;
    city: string;
}

let person: Person = {
    name: "John",
    age: 30,
    city: "New York"
};

Object Spread and Rest

TypeScript supports object spread and rest syntax:

// Object spread
let person = { name: "John", age: 30 };
let employee = { ...person, id: 123 };

console.log(employee); // Output: { name: "John", age: 30, id: 123 }

// Object rest
let { age, ...remaining } = employee;

console.log(remaining); // Output: { name: "John", id: 123 }

Conclusion

Understanding how to work with objects is crucial for building robust TypeScript applications. In this tutorial, we covered object creation, accessing properties, adding methods, defining object types, and utilizing object spread and rest syntax. With this knowledge, you can confidently work with objects in TypeScript and enhance your development skills.

Leave a Reply