TypeScript Object
In TypeScript, objects play a key role in organizing and manipulating data. They allow us to represent collections of key-value pairs, making our code more expressive and structured. In this article, we’ll learn TypeScript objects, their properties, and how to use their power effectively.
What Are TypeScript Objects?
An object in TypeScript is an instance that contains a set of key-value pairs. These pairs can hold various data types, including scalar values, functions, or even arrays of other objects. The Typescript object refers to any value that isn’t a primitive (string, number, bigint, boolean, symbol, null, or undefined). This is different from the empty object type { }, and also different from the global type Object.
Syntax:
let Name_of_object = {
object_property : value,
}
Parameters:
- Name_of_object: This is the name of the object.
- object_property: This is the property of the object or Key.
- value: This is the value of the property.
1. Object Literal Notation
Javascript
const person = { firstName: "Rahul" , lastName: "Kushwaha" , age: 30, }; console.log(`Hello, ${person.firstName} ${person.lastName}!`); |
Hello, Rahul Kushwaha!
In the example above, person
is an object with properties like firstName
, lastName
, and age
. We access these properties using dot notation.
2. Defining Object Types
In TypeScript, we represent object types using either interfaces or type aliases. These type templates ensure that objects adhere to a specific structure:
Using Interfaces:
Javascript
interface MyObject { company: string; type: string; solve: () => string; } const obj: MyObject & { [key: string]: any } = { company: 'w3wiki' , type: 'unique' , solve: function ( this : MyObject) { return `GFG is ${ this .company}, and it's ${ this .type}`; } }; // Calling function solve by // accessing through obj.solve() console.log(obj.solve()); // Adding one more field dynamically obj.location = "Noida"; // Printing the newly added field console.log(obj.location); |
Output
GFG is w3wiki, and its unique
Noida
In this above example, we have created an interface MyObject and another constant named obj, which has the type of MyObject and it is storing an object. we are calling the method which is defined in the object and printing the result in the console.
Using Type Aliases:
Javascript
type Product = { productId: string; name: string; price: number; }; const laptop: Product = { productId: "LAP123" , name: "Dell Inspiron" , price: 800, }; console.log(laptop); |
Output:
{
"productId": "LAP123",
"name": "Dell Inspiron",
"price": 800
}
Index Signatures:
For objects without a fixed set of properties, we can use index signatures. These allow dynamic property names:
Javascript
var nameAgeMap: { [index: string]: number } = {}; nameAgeMap[ "Jack" ] = 25; nameAgeMap[ "Mark" ] = 30; console.log(nameAgeMap); |
Output:
{
"Jack": 25,
"Mark": 30
}