0

Взял кусок кода для преобразования строки из csv файла в массив объектов. Указал всем переменным их типы, однако в части при распредлении object[header] = values[index] выдает ошибку

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
  No index signature with a parameter of type 'string' was found on type '{}'.ts(7053)

Разумеется я искал в просторах интернета как это исправить. Самое частое что видел как это исправить - добавить в object[header] - object[header as keyof typeof object] однако при таком использовании выдает ошибку - Type 'string' is not assignable to type 'never'.

Вот полная версия этой части кода:

import styles from './Input.module.scss'
import { FileInputProps } from './FileInput.props'
import cn from 'classnames'
import { useState, useEffect } from 'react'

export const FileInput = ({ array, setArray, ...props }: FileInputProps): JSX.Element => {

      const [content, setContent] = useState<string>('')

      const changeData = (e: any) => {
            const reader = new FileReader()
            reader.onload = async (e: any) => {
                  const text = (e.target.result)
                  setContent(text)
            }
            reader.readAsText(e.target.files[0])

            const headers: string[] = content.slice(0, content.indexOf("\n")).split(',')
            const rows: string[] = content.slice(content.indexOf("\n") + 1).split("\n")

            headers.pop()

            const arr: object[] = rows.map((row: string) => {
                  const values: string[] = row.split(',')
                  const element: object = headers.reduce((obj: object, header: string, index: number) => {
                        \/\/\/\/\/\/
                        obj[header] = values[index]
                        /\/\/\/\/\/\
                        return obj
                  }, {})
                  return element
            })

            console.log(arr)
      }

      return (
            <>
                  <input
                        type='file'
                        onChange={e => changeData(e)}
                  />

                  {content}
            </>
      );
}
1
  • в типе object нет ключей
    – Grundy
    27 янв 2023 в 13:01

1 ответ 1

1

В данном случае вместо object можно воспользоваться типом Record<string, string>

В этом случае можно использовать строки в качестве ключей.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.