gpt4 book ai didi

TypeScript:使用 0 个或多个参数调用重载的 asyncPipe

转载 作者:行者123 更新时间:2023-12-03 16:49:43 24 4
gpt4 key购买 nike

我有一个 asyncPipe像这样的功能:

export function asyncPipe<A, B>(
ab: (a: A) => MaybePromise<B>
): (a: MaybePromise<A>) => Promise<B>;
export function asyncPipe<A, B, C>(
ab: (a: A) => MaybePromise<B>,
bc: (b: B) => MaybePromise<C>
): (a: MaybePromise<A>) => Promise<C>;
export function asyncPipe<A, B, C, D>(
ab: (a: A) => MaybePromise<B>,
bc: (b: B) => MaybePromise<C>,
cd: (c: C) => MaybePromise<D>
): (a: MaybePromise<A>) => Promise<D>;
export function asyncPipe<A, B, C, D, E>(
ab: (a: A) => MaybePromise<B>,
bc: (b: B) => MaybePromise<C>,
cd: (c: C) => MaybePromise<D>,
de: (d: D) => MaybePromise<E>
): (a: MaybePromise<A>) => Promise<E>;

export function asyncPipe(...fns: Function[]) {
return (x: any) => fns.reduce(async (y, fn) => fn(await y), x);
}
我想这样称呼它:
const createRoute = (...middleware: Middleware[]) => async (
request: Response,
response: Request
) => {
try {
await asyncPipe(...middleware)({
request,
response
});
} catch (e) {
console.error(e);
response.status(500);
response.json({
error: "Internal Server Error"
});
}
};
哪里 Middleware是一种函数类型,用于接收至少具有键 request 的对象和 response ,但可能会向对象添加更多数据。
{
request,
response,
user, // 👈 added by some middleware
db, // 👈 added by another middleware
/* ... more keys added by middleware */
}
TypeScript 提示并说 Expected 1-6 arguments, but got 0 or more.在我打电话的线路中 asyncPipe .我怎么能说,那 middleWare将总是至少一个参数,或者重载它,所以它也接受 0 个参数?
更新:
我试过 Rob 的回答是这样的:
export function asyncPipe<A>(...fns: Function[]): MaybePromise<A>;
但这阻止了我所有的 asyncPipe特定的测试失败。顺便说一句,测试看起来像这样:
import { describe } from "riteway";

import { asyncPipe } from "./asyncPipe";

const asyncInc = (n: number) => Promise.resolve(n + 1);
const inc = (n: number) => n + 1;

describe("asyncPipe()", async assert => {
assert({
given: "a promise",
should: "pipe it",
actual: await asyncPipe(asyncInc)(1),
expected: 2
});

assert({
given: "two promises",
should: "pipe them",
actual: await asyncPipe(asyncInc, asyncInc)(1),
expected: 3
});

assert({
given: "three promises",
should: "pipe them",
actual: await asyncPipe(asyncInc, asyncInc, asyncInc)(1),
expected: 4
});

assert({
given: "promises mixed with synchronous function",
should: "pipe them",
actual: await asyncPipe(asyncInc, inc, asyncInc)(1),
expected: 4
});

{
const throwInc = (n: number) => Promise.reject(n + 1);

assert({
given: "promises where one throws",
should: "pipe them",
actual: await asyncPipe(asyncInc, throwInc, asyncInc)(1).catch(x => x),
expected: 3
});
}
});

最佳答案

添加“零个或多个”定义。例如,您可以公开实现的定义:

// Previous definitions
export function asyncPipe(...fns: Function[]);

export function asyncPipe(...fns: Function[]) {
return (x: any) => fns.reduce(async (y, fn) => fn(await y), x);
}

关于TypeScript:使用 0 个或多个参数调用重载的 asyncPipe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60437473/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com