GregRos / parjs

JavaScript parser-combinator library
MIT License
271 stars 18 forks source link

refactor: replace overloaded functions with mapped types #72

Open barona-mika-vilpas opened 9 months ago

barona-mika-vilpas commented 9 months ago

Currently parjs has some functions that are overloaded, such as this:

export function pipe<T, T1, T2, T3, T4, T5, T6>(
    source: ImplicitParjser<T>,
    cmb1: ParjsCombinator<T, T1>,
    cmb2: ParjsCombinator<T1, T2>,
    cmb3: ParjsCombinator<T2, T3>,
    cmb4: ParjsCombinator<T3, T4>,
    cmb5: ParjsCombinator<T4, T5>,
    cmb6: ParjsCombinator<T5, T6>
): Parjser<T6>;

The goals:

  1. see if it's possible to get rid of overloading and replace it with something else, such as a map type or a tuple type
type MapParjsers<Vs extends any[] = {
    [K in keyof Vs]: ImplicitParjser<Vs[K]>
}

export function then<Head, Tail extends any[]>(first: ImplicitParjser<Head>, ...following: MapParjsers<Tail>): ParjsCombinator<[Head, ...Tail]>
  1. make sure to preserve the type inference! Calling these must be type safe, i.e. the return type must be perfectly inferred (right now it's good)

This came up in https://github.com/GregRos/parjs/pull/64#issuecomment-1810698810

barona-mika-vilpas commented 9 months ago

idea: There are some interesting suggestions in the comment section here. They might be helpful: https://dev.to/futuresight/how-2-typescript-get-the-last-item-type-from-a-tuple-of-types-3fh3