angular error troubleshoot

Type cannot be used as an index type

This tutorial guides you on how to resolve Angular error “Type cannot be used as an index type”. Are you facing Type cannot be used as an index type while using model in angular component ? Let’s see what had gone wrong.

Type cannot be used as an index type

When tried to create ingredients array property with an instantiated values of Ingredient, by mistake used objects as indexes of ingredients array instead of number. This resulted with following error Type cannot be used as an index type. Here by mistake object type is used as an index.

ingredients: Ingredient[
  new Ingredient('Oranges', 5),
  new Ingredient('Lemons', 10),
];

Error: Type ‘new () => Ingredient’ cannot be used as an index type

(alias) class Ingredient
import Ingredient
Type 'new () => Ingredient' cannot be used as an index type.ts(2538)
'(' expected.ts(1005)

Fix:

To fix the above error, you need to create ingredients array and initialize it properly as shown below. Therefore, in the following fix we haven’t used objects as indexes instead the indexes (numbers) are created dynamically.

The real issue was incorrect array declaration and initialization or usage of model in the angular component.

ingredients: Ingredient [] = [
   new Ingredient('Apples', 8),
   new Ingredient('Tomatoes', 12),
];

That’s it. Try to run your angular application, you can see that the error type cannot be used as an index type should have gone away.

Hope it helped 🙂

Also See:

References:

Leave a Reply

avatar
  Subscribe  
Notify of