Just delving into typescript and attempting to create a parser combinator library. Initially, handling types and generics was straightforward until I encountered an issue.
// Representing the returned value of the parser with generic T
class Parser<T> {
...
}
// Merging two parsers into one tuple using this function
function pair<P1 extends Parser<A>, P2 extends Parser<B>, A, B>(
parser1: Parser<A>,
parser2: Parser<B>
): Parser<{ fst: A, snd: B }> {
...
}
// Transforming a Parser<A> to a Parser<B> via the mapping of A => B
function map<P extends Parser<A>, F extends (a: A) => B, A, B>(
parser: P, mapFn: F
): Parser<B> {
...
}
Here arises the issue:
// Similar to `pair` but with the parser value as A instead of {fst: A, snd: B}
function left<P1 extends Parser<A>, P2 extends Parser<B>, A, B>(
parser1: P1,
parser2: P2
): Parser<A> {
return map(pair(parser1, parser2), (a: unknown): A => (a as {fst: R1, snd: R2}).fs );
}
The provided `left` function compiles, however, it is unclear why typescript does not infer that the unknown
should be {fst: A, snd: B}
. Is this an issue with typescript or simply my misunderstanding of how typescript generics operate.
Thanks in advance.
EDIT
Added reproducible playground:
You can access the link for the reproducible code.