pgsql-ast-parser icon indicating copy to clipboard operation
pgsql-ast-parser copied to clipboard

`parse` function with `ParseOptions` argument has incorrect declared return type

Open gthb opened this issue 3 years ago • 0 comments

I noticed that if you pass an ParseOptions argument with an entry to parse(), it will return a single AST node, not an array of them:

    // always return an array of statements.
    if (!entry && !Array.isArray(parsed)) {
        parsed = [parsed]

That makes the return type for that overload incorrect:

export function parse(sql: string, options?: ParseOptions): Statement[];

... so usage with an options argument raises a type check violation in my code:

    const parsedQuery = parse(queryWithFrom, { entry: 'selection' });
    if (parsedQuery.type !== 'select') {
        ...

... saying Property 'type' does not exist on type 'Statement[]' (but this call will return a single AST node)

The overload signature should be:

export function parse(sql: string, options?: ParseOptions): any;

(or else something like Statement[] | AstNode I guess, if there's a union type like AstNode somewhere...)

In the same way, parseWithComments should have its ast return type attribute typed as any (or Statement[] | AstNode):

export function parseWithComments(sql: string, options?: ParseOptions): { ast: any; comments: PGComment[] } {
    return trackingComments(() => parse(sql, options));
}

or else it should have overloads like the parse function does.

gthb avatar Jul 01 '22 09:07 gthb