node-csv icon indicating copy to clipboard operation
node-csv copied to clipboard

Function parse returns "any" - Could it be made generic?

Open bennycode opened this issue 1 year ago • 4 comments

Summary

I am using csv-parse in a TypeScript project the following way:

import {parse} from 'csv-parse/sync';

const records = parse(input, {
  columns: true,
  delimiter: ',',
  skip_empty_lines: true
});

In my TS code the records are of type any because parse has the following type definiton:

sync.d.cts

declare function parse(input: Buffer | string, options?: Options): any;

Could the parse function accept a type argument to define the type its output? I am thinking of something like this:

declare function parse<T>(input: Buffer | string, options?: Options): T;

bennycode avatar Nov 23 '23 08:11 bennycode

Like for any TypeScript request, please consider that I am no TS expert. Your suggestion seems good but I would enjoy feedbacks from the community first. Anyone ?

Also, I suspect the change to not be backward compatible and to break a lot of code base. In such case, we will generate a new major version and, to avoid many upgrade, we shall apply the same change to every concerned function in each of the package managed by the CSV project.

wdavidw avatar Nov 23 '23 09:11 wdavidw

We can make this change backward-compatible by using a default type argument, i.e.

declare function parse<T = any>(input: Buffer | string, options?: Options): T;

bennycode avatar Nov 23 '23 09:11 bennycode

Sounds good, I'll give it a try, hopefully soon

wdavidw avatar Nov 23 '23 09:11 wdavidw

Hi 👋 I add my two cents on this 😄 What would you think about returning unknown[] instead ? the idea is that we can't be sure that the content of the file does match the generic given, so actually using a generic would be the same that what we have today, it's just a cast 🤷 whereas with the unknown, we first have to make sure that the content of the file does match the expected type, and then with type guards we're sure that our type match our content.

Also, unless I'm wrong, only an array can be returned by the parse function, so shouldn't we return either an unknown[] or if we want to stick to generics, return a T[] ?

0xCAFEADD1C7 avatar Mar 27 '24 16:03 0xCAFEADD1C7