Chevrotain / chevrotain

Parser Building Toolkit for JavaScript
https://chevrotain.io
Apache License 2.0
2.44k stars 199 forks source link

Improved type-safety for OR #1986

Open LaurensRietveld opened 9 months ago

LaurensRietveld commented 9 months ago

Take this OR statement:

const result = this.OR([
  {ALT: () => 1},
  {ALT: () => 'string'}
])

The type of result is any, where I'd expect it to be of type string | number. Is there a reason why the returntype of the ALT functions isn't used instead?

ps. Many thanks for this library! Enjoying the type safety and performance

LaurensRietveld commented 9 months ago

Note that I managed to work around this myself by extending the OR function and its types:

  public OR<A extends Array<IOrAlt<any>>>(alt: A) {
    return super.OR(alt) as ReturnType<A[number]["ALT"]>;
  }

I understand that my types are incomplete (I'm only including the IOrAlt types and not the OrMethodOpts types), but it suffices for my usecase

bd82 commented 6 months ago

Hello @LaurensRietveld

Could this be extended in a generic manner to improve the Chevrotain types?