ts-pegjs icon indicating copy to clipboard operation
ts-pegjs copied to clipboard

Alternative of strings returns Readonly<any>

Open SirPL opened this issue 2 years ago • 1 comments

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>.

SirPL avatar Nov 13 '21 08:11 SirPL

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>"
  }
}

pjmolina avatar Mar 17 '22 11:03 pjmolina