DefinitelyTyped/types/koa-router
Anton Astashov 1645790bef @types/koa-router: Typesafe middlewares prepending
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?
2019-02-23 13:36:22 -06:00
..
index.d.ts @types/koa-router: Typesafe middlewares prepending 2019-02-23 13:36:22 -06:00
koa-router-tests.ts @types/koa-router: Typesafe middlewares prepending 2019-02-23 13:36:22 -06:00
tsconfig.json
tslint.json