chevrotain
chevrotain copied to clipboard
Improved type-safety for OR
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
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
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