In TypeScript, an index type is a way to specify that an object should have keys of a specific type and values of another specific type. You can create an index type using square brackets ‘[]‘ notation in an interface or a type alias. Let’s see an example:
interface StringIndexObject {
[key: string]: number;
}
In this example, we created an interface called ‘StringIndexObject‘, in which any object of this type will have keys of type ‘string‘ and values of type ‘number‘.
Here’s an example of how to use this ‘StringIndexObject‘ interface:
const myObject: StringIndexObject = {
a: 1,
b: 2,
c: 3,
};
const valueA: number = myObject['a'];
Now let’s say you want to create an index type for an object with keys of type ‘number‘ and values of type ‘string‘. Here’s how you can do this using a type alias:
type NumberIndexObject = {
[key: number]: string;
};
Using this type alias, let’s see an example:
const myOtherObject: NumberIndexObject = {
1: "a",
2: "b",
3: "c",
};
const valueB: string = myOtherObject[2];
In addition, there is a special type in TypeScript called ‘keyof‘ that can be used to create index types based on the keys of another type. Here’s an example of how you can use ‘keyof‘ to access the properties of an object:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const sampleObject = { a: 1, b: 'hello' };
const numericValue: number = getProperty(sampleObject, 'a');
const stringValue: string = getProperty(sampleObject, 'b');
In this example, we’re using generic types ‘T‘ and ‘K‘ to create a flexible function that can get a property from various objects of different types. The type ‘K‘ is constrained to be one of the keys of the type ‘T‘, using the ‘keyof‘ keyword. Then, ‘T[K]‘ is used to specify the return type which corresponds to the value type *specific to the key*.
Remember that index types are powerful constructs in TypeScript that make it possible to model the shape and behavior of objects in a more versatile and dynamic way. This allows you to create more robust and type-safe code.