Search code examples
jsontypescriptcsvpapaparse

How to type the result of Papa.parse?


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))
});

Solution

  • 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