Skip to main content

Archive

Show more

Objects in TypeScript

Objects in TypeScript

In TypeScript, an object is a data structure that can hold multiple values in the form of key-value pairs. Objects are a fundamental part of TypeScript and allow you to organize and manage data effectively. This guide covers how to define, manipulate, and work with objects in TypeScript.


Defining Objects

Objects in TypeScript can be defined using object literals or interfaces. Here’s a basic example:


let person: {
  name: string;
  age: number;
  isEmployed: boolean;
} = {
  name: "John",
  age: 30,
  isEmployed: true
};
console.log(person);

You can also define objects using interfaces:


interface Person {
  name: string;
  age: number;
  isEmployed: boolean;
}

let person: Person = {
  name: "John",
  age: 30,
  isEmployed: true
};
console.log(person);

Object Properties and Methods

Objects can have properties and methods. Properties are used to store data, while methods are functions associated with the object. Here’s how to define and use properties and methods in objects:


interface Person {
  name: string;
  age: number;
  greet(): void;
}

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

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

Optional and Readonly Properties

TypeScript allows you to define optional properties and readonly properties in objects. Optional properties are not required to be present, while readonly properties cannot be modified after they are initialized:


interface Person {
  name: string;
  age?: number; // Optional property
  readonly id: number; // Readonly property
}

let person: Person = {
  name: "John",
  id: 12345
};

// person.age = 30; // This is valid
// person.id = 67890; // Error: Cannot assign to 'id' because it is a read-only property

Index Signatures

Index signatures allow you to define objects with dynamic property names. This is useful when you want to work with objects where the property names are not known in advance:


interface Dictionary {
  [key: string]: string;
}

let dict: Dictionary = {
  "firstName": "John",
  "lastName": "Doe"
};

console.log(dict["firstName"]); // Output: John

Type Assertion

Type assertion allows you to override TypeScript's inferred type of an object. This can be useful when you know more about the object’s type than TypeScript can infer:


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

let person = {} as Person;
person.name = "John";
person.age = 30;

console.log(person); // Output: { name: 'John', age: 30 }

Conclusion

Objects in TypeScript are versatile and powerful, allowing you to model real-world entities and manage data efficiently. By understanding how to define and use objects, including their properties, methods, and special features like optional and readonly properties, you can create more robust and maintainable TypeScript applications.

Comments