Index signatures in typescript thumbnail

Index signatures in typescript

index signatures in TypeScript allows to define the types of properties that are not known in advance, but they can be accessed using strings or numbers as keys

The index signature in TypeScript allows you to define types of properties that are unknown in advance, but can be accessed using strings or numbers. A feature like this is useful when the name of a property of an object is dynamic or unknown.


Here is an example:


interfaces.ts
interface food {
[key: string]: string | number;
}

const fruits: food = {
orange: 2,
apple: 3,
banana: "empty",
};


Here another example:



interfaces.ts
interface ItemPrices {
[itemName: string]: number;
}

const prices: ItemPrices = {
apple: 1.0,
banana: 0.5,
orange: 0.8,
};

const itemName = "apple";
const priceOfApple = prices[itemName];
console.log(`The price of ${itemName} is $${priceOfApple}`);


When working with objects with varying property sets, index signatures allow you to work with them without explicitly declaring their names.In particular, it comes in handy when dealing with.

codecillionlogo

codecillion

Copyright ©2025 , all rights reserved