chevrotain icon indicating copy to clipboard operation
chevrotain copied to clipboard

Improved type-safety for OR

Open LaurensRietveld opened this issue 2 years ago • 2 comments

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 avatar Sep 06 '23 21:09 LaurensRietveld

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

LaurensRietveld avatar Sep 06 '23 21:09 LaurensRietveld

Hello @LaurensRietveld

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

  • https://github.com/Chevrotain/chevrotain/blob/a0a3856069c257c77dc3183efa0048a41ab8f88b/packages/types/api.d.ts#L409-L410

bd82 avatar Dec 31 '23 13:12 bd82