Open In App

TypeScript Object Type Index Signatures

Last Updated : 25 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn about Object Type Index Signatures in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, index signatures allow you to define object types with dynamic keys, where the keys can be of a specific type, and the corresponding values can be of another type. This is particularly useful when you want to work with objects that have properties that are not known at compile-time but follow a specific pattern.

Syntax:

type MyObject = {
[key: KeyType]: ValueType;
};

Where-

  • MyObject is the name of the object type you are defining.
  • KeyType is the type of key that can be used to access properties in the object.
  • ValueType is the type of the values associated with the keys.

Example 1: In this example, Dictionary is an object type with an index signature [word: string]: string. which means it can have keys of type string and values of type string. myDictionary is an instance of a Dictionary with three key-value pairs. You can access and modify values using dynamic keys within the specified type constraints.

 

Javascript




type Dictionary = {
    [word: string]: string;
};
  
const myDictionary: Dictionary = {
    "apple": "a fruit",
    "banana": "another fruit",
    "car": "a vehicle",
};
// Outputs: "a fruit"
console.log(myDictionary["apple"]);


Output:z34

Example 2: In this example, StudentGrades is an object type with an index signature [subject: string]: number;, which means it can have keys of type string (representing subjects) and values of type number (representing grades). grades is an instance of StudentGrades with three subject-grade pairs.

Javascript




type StudentGrades = {
    [subject: string]: number;
};
  
const grades: StudentGrades = {
    "Math": 90,
    "English": 85,
    "History": 78,
};
  
// Outputs: 90
console.log(grades["Math"]);


Output: z35



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads