How to type the result of Papa.parse?
Asked Answered
S

1

6

I'm using Papaparse with Typescript to parse a local file and it works well.

I'm doing it like this:

parse(file, {
    header: true,
    dynamicTyping: true,
    complete: (results) =>
        console.log(results)
});

But I want to strongly type the result. I have an interface and the result of the parse will always return me an array of objects with the following properties:

export interface Person {
    name: string;
    age: number;
    location: string;
}

How can we type the result ?

I found this Reddit thread and I tried their solution but it doesn't work:

parse<Person[]>(file, {
    header: true,
    dynamicTyping: true,
    complete: (results: Person) =>
        console.log(JSON.stringify(results.age))
});
Sambo answered 27/4, 2022 at 9:52 Comment(0)
S
6

The complete callback doesn't return a Person object.

The function should look like:

import {ParseResult} from 'papaparse';

function(results: ParseResult<Person>){ ...}

See https://www.papaparse.com/docs#results and line 255 in the typings file

Stretch answered 27/4, 2022 at 10:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.