Encountering an issue where row[header.key]
is displaying the error message
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'DataType'
. I prefer not to use type:any
and instead would like to know what to pass in here.
Your assistance is greatly appreciated. Thank you in advance.
export interface HeaderType {
label: string;
key: string
}
export interface DataType {
isImported: string;
type: string;
entityId: string | undefined;
actor?: string | undefined;
additionalInformation?: { [key: string]: string } | undefined;
}
const convertToCsv = (headers: Array<HeaderType>, data: Array<DataType>) => {
const csvRows = [];
const headerValues = headers.map(header => header.label);
csvRows.push(headerValues.join(','));
data?.forEach(row => {
const rowValues = headers.map(header => {
let escaped;
if (typeof row[header.key] === 'object') {
const str = JSON.stringify(row[header.key], null, 1);
escaped = str?.replace(/"/g, '');
} else if (row[header.key] && /"/g.test(row[header.key])) {
escaped = row[header.key].replace(/"/g, '');
} else {
escaped = row[header.key] ? row[header.key].replace(/"/g, '\\"') : '';
}
return `"${escaped}"`;
});
csvRows.push(rowValues.join(','));
});
return csvRows.join('\n');
};
const generateCSV = (
header: Array<HeaderType>,
data: Array<DataType> ,
) => convertToCsv(header, data);
export default generateCSV;