【发布时间】:2020-12-30 19:01:10
【问题描述】:
我正在开发一个解析器组合器库,我需要实现一个 map 函数,该函数采用元组中的 N 解析器,以及一个采用这些 N 参数并返回解析器的函数,该解析器解析为函数的返回类型。
<A, B, Z>(ps: [a: Parser<A>, b: Parser<B>], f: (a: A, b: B) => Z): Parser<Z>
<A, B, C, Z>(ps: [a: Parser<A>, b: Parser<B>, c: Parser<C>], f: (a: A, b: B, c: C) => Z): Parser<Z>
// etc
我正在寻找一种方法来为任意数量的解析器定义 map 函数的类型。
我已经有了这个函数的实现,除了类型。
最小的复制:
type Parser<T> = () => T;
const string: Parser<string> = null as any;
const number: Parser<number> = null as any;
type MapN = {
<A, B, Z>(ps: [a: Parser<A>, b: Parser<B>], f: (a: A, b: B) => Z): Parser<Z>,
<A, B, C, Z>(ps: [a: Parser<A>, b: Parser<B>, c: Parser<C>], f: (a: A, b: B, c: C) => Z): Parser<Z>,
}
const mapN: MapN = null as any;
const p1 = mapN([string, number], (a, b) => [a, b] as const);
const p2 = mapN([string, number, number], (a, b, c) => [a, b, c] as const);
// const p3 = mapN([string, number, string, string], (a, b, c, d) => [a, b, c, d] as const);
// const p4 = mapN([string, number, string, number, number], (a, b, c, d, e) => [a, b, c, d, e] as const);
有没有办法为任意数量的参数定义这个函数,同时保持类型安全?
【问题讨论】:
标签: typescript