Papaparse and Typescript

862 views Asked by At

I am using React and Typescript to build a CSV import app. After initializing my project with Typescript support using npx create-react-app my-app --template typescript, I followed this how-to guide: https://www.geeksforgeeks.org/how-to-read-csv-files-in-react-js/. I added PapaParse using yarn, which worked on a standard React app but produced multiple errors on the Typescript version.

In the handleParse function below:

const handleParse = () => {

  // If user clicks the parse button without
  // a file we show a error
  if (!file) return setError("Enter a valid file");

  // Initialize a reader which allows user
  // to read any file or blob.
  const reader = new FileReader();

  // Event listener on reader when the file
  // loads, we parse it and set the data.
  reader.onload = async ({ target }) => {
    const csv = Papa.parse(target.result, { header: true });
    const parsedData = csv?.data;
    const columns = Object.keys(parsedData[0]);
    setData(columns);
  };
  reader.readAsText(file);
};

I encounter the following errors:

  • const csv = Papa.parse(target.result, { header: true }); generates the following errors:
    • target: "TS18047: 'target' is possibly 'null'."
    • target.result: "TS2769: No overload matches this call.", "Argument of type 'string | ArrayBuffer | null' is not assignable to parameter of type 'unique symbol'.", "Type 'null' is not assignable to type 'unique symbol'."
  • const parsedData = csv?.data; generates the error "Property 'data' does not exist on type 'never'."
  • setData(columns); generates the error "TS2345: Argument of type 'string[]' is not assignable to parameter of type 'SetStateAction<never[]>'."
  • reader.readAsText(file); generates the error "Argument of type 'string' is not assignable to parameter of type 'Blob'."
  • rowsArray.push(Object.keys(d)); generates the error "Argument of type 'string[]' is not assignable to parameter of type 'never'."
  • rowsArray.push(Object.keys(d)); generates the error "Argument of type 'unknown' is not assignable to parameter of type 'object'."
  • valuesArray.push(Object.values(d)); generates the error "Argument of type 'unknown[]' is not assignable to parameter of type 'never'."
  • `valuesArray.push(Object.values(d)); generates the error "Argument of type 'unknown' is not assignable to parameter of type '{}'."
  • setParsedData(results.data); generates the error "Type 'unknown' is not assignable to type 'never'."

I am pretty sure the issues comes from TypeScript's less lenient type handling but - being new to React - I am not sure how to fix this. Can anyone please point me in the right direction?

0

There are 0 answers