我正在为一个项目的Express创建一个路由处理程序创建器,我试图将其创建为您可以在传递路由处理程序回调之前将任意断言作为初始参数传递.类似于这样的:
const myHandler = makeHandler(assertion1(), assertion2(), (data, req, res, next) => {
// data is an array of the results of the assertions
});
我可以得到我希望类型"工作"的某种版本:
// express namespace omitted for brevity; see playground link above.
type Assertion<T = unknown> = (req: express.Request) => T;
type ReturnTypes<A extends ReadonlyArray<Assertion>> = {
[K in keyof A]: ReturnType<A[K]>;
};
function assertion1<T extends object>(arg: T) {
return () => arg
}
function assertion2() {
return () => "yes"
}
const a = assertion1({ something: "yes" })
const b = assertion2()
// This type works as expected: it is [{ something: string }, string]
type d = ReturnTypes<[typeof a, typeof b]>
然而,当我试图将其作为上述参数makeHandler
的可变版本时,有些东西似乎不起作用,并且上例中的data
类型是unknown[]
:
// the logic for `makeHandler` is omitted for brevity
declare function makeHandler<
Assertions extends Assertion<unknown>[]
>(...assertionsAndCb: [...Assertions, HandlerCb<ReturnTypes<Assertions>>]): void
// `data` here doesn't seem to be typed correctly. For some reason it's of type unknown[], rather than
// the same as type `d` above.
makeHandler(assertion1({ hey: "what"}), assertion2(), (data, req) => {
return { response: {} }
})
我读过一些关于如何处理zip
之类的内容(并且我的函数在很大程度上基于这个要点),但我很难让实际类型正确通过.我在这里是否遗漏了一些东西--例如,一些我不允许正确推断的通用性?