Open In App

TypeScript Object Type Index Signatures

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-



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.

 






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:

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.




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

Output:


Article Tags :