mirror of
https://github.com/gosticks/DefinitelyTyped.git
synced 2025-10-16 12:05:41 +00:00
It's sometimes useful to prepend middlewares to the route handler, when
we want to register some middlewares only for particular routes.
Like:
```ts
router.get("/foo",
(ctx: Koa.Middleware<IFoo>, next) => {
ctx.state.foo = "foo";
return next();
},
(ctx, next) => {
// ctx here knows `ctx.state.foo` is `string`
// ...
}
);
```
Unfortunately, currently we can't infer that `ctx` there would have
`state.foo`. All middlewares/route-handlers should have the same type
currently.
It seems to be impossible to do that in the general case (for any number
of prepended middlewares), but we could have a special case for 2
middlewares, and if we have to prepend several middlewares - we could
use `koa-compose` to combine them into one, and still do that in a
typesafe way.
Like:
```ts
router.get("/foo",
compose([
(ctx: Koa.Middleware<IFoo>, next) => {
ctx.state.foo = "foo";
return next();
},
(ctx: Koa.Middleware<IBar>, next) => {
ctx.state.bar = "bar";
return next();
}
]),
(ctx, next) => {
// ctx here knows `ctx.state.foo` is `string`
// and `ctx.state.bar` is `string`.
}
);
```
Changes in this PR add that special case for one prepended middleware
for all route methods (`get`, `post`, `head`, etc).
It's not a breaking change - we keep old types here, we only add a
special more type-correct way of prepending one middleware before a
route handler.
What do you think?
|
||
|---|---|---|
| .. | ||
| index.d.ts | ||
| koa-router-tests.ts | ||
| tsconfig.json | ||
| tslint.json | ||