Indexable type for arrays in TypeScript
In TypeScript, you can create interfaces that specify the type of key-value pairs in arrays and objects. This type is called indexable.
Let's see in practice. Let's create an interface IArray, which will define a key-element pair for an array. We'll specify that the array key will be a number (we have no other options here), and the value will be a string:
interface IArray {
[index: number]: string;
}
Now let's declare a variable arr with our indexed type:
let arr: IArray;
Let's assign our variable a value in the form of an array of strings:
let arr: IArray = ['a', 'b', 'c'];
Now, if you make numbers as array elements, TypeScript will throw an error:
let arr: IArray = [1, 2, 3]; //
Create an interface that describes an array with values as numbers.