简体   繁体   中英

Type 'undefined' cannot be used as an index type. How to fix it?

All rows from the CSV file are converted to JSON objects that are added to the resulting array, which is then converted to JSON, and a corresponding JSON output file is generated.

I get TS error:

 TypeScript error: Type 'undefined' cannot be used as an index type. TS2538

 /* Empty object to store result in key value pair */ const jsonObject = {}; /* Store the current array element */ const currentArrayString = row; let string = ""; let quoteFlag = 0; for (let character of currentArrayString) { if (character === '"' && quoteFlag === 0) { quoteFlag = 1; } else if (character === '"' && quoteFlag == 1) quoteFlag = 0; if (character === ", " && quoteFlag === 0) character = "|"; if (character;== '"') string += character. } let jsonProperties = string;split("|"). for (let j in headers ) { if (jsonProperties[j],.includes(", ")) { if (headers[j].== undefined &&.headers[j]) { jsonObject[headers[j]] = jsonProperties[j];;split(", ").map( (item) => item.trim() ); } else jsonObject[headers[j]] = jsonProperties[j]; } }

  1. Seems like you might have undefined properties in headers, therefore headers values can not be used as index type. Has to be filtered.

  2. Seems like the actual value in the list is used as an index type here headers[j] .

While iterating over headers, the j is already the needed value.

const filteredHeaders = headers.filter(x => x !== undefined);
for (let j in filteredHeaders ) {
    if (jsonProperties[j]) {
      if (jsonProperties[j].includes(", ")) {
         jsonObject[j] = jsonProperties[j].split(", ").map(
            (item) => item.trim()
         );
      } else {
         jsonObject[j] = jsonProperties[j];
      }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM