Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
bennycode opened this issue Nov 23, 2023 · 4 comments
Open

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

bennycode opened this issue Nov 23, 2023 · 4 comments

Comments

@bennycode
Copy link

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;
@wdavidw
Copy link
Member

wdavidw commented Nov 23, 2023

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.

@bennycode
Copy link
Author

bennycode commented Nov 23, 2023

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;

@wdavidw
Copy link
Member

wdavidw commented Nov 23, 2023

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

@0xCAFEADD1C7
Copy link

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[] ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants