metadevpro/ts-pegjs

Alternative of strings returns Readonly<any>

SirPL opened this issue · 1 comments

SirPL commented

Minimal example of a problem:

PEGjs code:

START
  = "a"
  / "b"

Types definition:

{
  "returnTypes": {
    "START": "string"
  }
}

Example above, run in --cache mode, produces invalid TypeScript code. peg$parseSTART's function type should be string (as declared in returnTypes) because the only valid return of START rule is a string.
However if neither "a" nor "b" is found (parsed), peg$FAILED is returned which type is Readonly<any>. In the result the return type of peg$parseSTART function is string|Readonly<any>.

The parser is intended to be used this way, with a try/catch:

try {
    const sampleOutput = parse('my sample...');
} catch (ex: SyntaxError) {
    // Handle parsing error
    // [...]
}

If your parser only recognizes a OR b and lets say you feed it c you will get a SyntaxError exception.
The typing provided here in the plugin is up to you:

You can force the type if you need it doing:

{
  "returnTypes": {
    "START": "string | Readonly<any>"
  }
}