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)
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 🙂
- Declare model class and use in Angular component : Typescript
- Add a Responsive Bootstrap Navigation Bar in Angular 9
- Set default value in the dropdown list in Angular 9
- Best way to delete components in Angular 9 with CLI ?
- HTML Property Binding in Angular : Data Binding
- Create custom events and fire in Angular 9 with EventEmitter – Example
- ERROR in multi /bootstrap.min.css ./src/styles.css in Angular 9
- Bind selected element from drop down to an object in Angular 9
- Create common app-header component in Angular 9
- How to stop generation of .spec.ts test files using Angular CLI ?
- Emmet in Visual Studio Code not working ?
- Angular: Quickly create div classes in Visual Studio Code editor
- Angular CLI command to generate model in Angular 9
- How to check your installed angular version ?