Home > Blockchain >  Element implicitly has an 'any' type because expression of type 'string' can
Element implicitly has an 'any' type because expression of type 'string' can

Time:01-30

Here i'm facing row[header.key] is showing the Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'DataType' issue i don't want to use type:any instead of any what can pass here.

Please help me thanks 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');
};

CodePudding user response:

The row[header.key] expression's absence of type information is the cause of this problem. You must convert the row[header.key] type to string in order to address the issue. This may be achieved by following the expression with the type assertion operator as string, as in:

Here's the updated code with the fix:

const rowValue = row[header.key] as string;

CodePudding user response:

You can use keyof DataType for key type

like this :

export interface HeaderType {
 label: string; 
 key: keyof DataType
}

Playground

I changed your code a little to handle type checking in row[header.key] in working with that as a string

sth like this

let str = row[header.key] as string
  • Related