Search code examples
node.jssonarqube

error TS2538: Type 'CCCustomer' cannot be used as an index type


For below mentioned code facing error as error TS2538: Type 'CCCustomer' cannot be used as an index type. with let index in ccCustomerList its working fine but in sonarqube received issue as Use "for...of" to iterate over this "Array". any alternative way available for this.

let data:Array<Customer>;

for (const index of CustomerList) {
    const Customer = CustomerList[index];
    const List: Array<string> = [];

Solution

  • In your loop, the index variable is not really an index of the array, but it's an object from the Customerlist, this is how for of works and that's why you get the error stating you can't use an object as an index.

    So you don't need to get the customer from the CustomerList array since it's already there in your index variable.

    Rename index to Customer and remove this line:

    const Customer = CustomerList[index];
    

    Replace all CustomerList[index] with Customer in your code.

    Example

    for (const Customer of CustomerList) {
      const guidList: Array<string> = [];
      // Use Customer object
    

    More information

    Update

    If you need to use an index use a regular loop or add Array.entries() to the current loop which returns the index and the value (just remove it if not needed).

    Example

    for (const [index, value] of CustomerList.entries()) {
      const Customer = CustomerList[index];
      const guidList: Array<string> = [];