Open In App

TypeScript Array keys() Method

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

TypeScript keys() method is not directly available on arrays. Instead, you can use the keys() method from the Object class to get the keys of an array. When applied to an array, Object.keys() returns an array containing the string representations of the indices.

Syntax:

array.keys(); 

Parameter:

  • The keys() method doesn’t accept any parameters.

Return Value:

  • It returns an Array Iterator object that contains the keys (indices) of the array.

Example 1: Here, arrayKeys will be an array containing the indices of myArray (‘0’, ‘1’, ‘2’), because arrays in JavaScript are essentially objects where the indices are treated as keys.

Javascript




const myArray: string[] =
    ['apple', 'banana', 'orange'];
 
// Using Array.keys() to get array indices
const arrayIndices: number[] =
    Array.from(myArray.keys());
 
console.log(arrayIndices);


Output:

0
1
2

Example 2: Here, we will get the key and the value of the given string array.

Javascript




// Here we are defining a string
// array with type annotations
const names: string[] =
    ["Pankaj", "Ram", "Shravan", "Jeetu"];
 
for (const key of names.keys()) {
    // Type assertion for key
      console.log(`Index: ${key}, Name: ${names[key as number]}`);
}


Output:

Index: 0, Name: Pankaj
Index: 1, Name: Ram
Index: 2, Name: Shravan
Index: 2, Name: Jeetu

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads