I'm starting to learn about typescript and I tried to make an parser combinator library, at first types and generics where easy, but an issue appeared.
// The generic T represents the value the parser returns
class Parser<T> {
...
}
// This function combines the two parsers in one tuple
function pair<P1 extends Parser<A>, P2 extends Parser<B>, A, B>(
parser1: Parser<A>,
parser2: Parser<B>
): Parser<{ fst: A, snd: B }> {
...
}
// Maps a Parser<A> to a Parser<B> through A => B
function map<P extends Parser<A>, F extends (a: A) => B, A, B>(
parser: P, mapFn: F
): Parser<B> {
...
}
Here is where I have the issue:
// Like pair but the value of the parser is 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 but I don't understand why typescript cannot infer that the unknown should be {fst: A, snd: B}, is this a typescript issue or just me mistaking how typescript generics work.
Thanks in advance.
EDIT
Added reproducible playground:
Here is the link reproducible