При использование middleware типизация body исчезает и появляется ошибка. Без него ошибки не наблюдается, я полагаю TypeScript сворачивает типы в более общий интерфейс и затем body отбрасывается, но почему это происходит мне не понятно. Что бы словить ошибку нужно раскомментить строку с middleware.
TS Playground
interface Schema<T> { t: T }
declare const s: Schema<{ hello: string }>
interface BaseContext { readonly request: any }
type Middleware = (context: BaseContext, next: () => Middleware) => any
interface RouteOptions { readonly body?: any; readonly middleware?: Middleware[]; }
type SpecifyContext<C extends BaseContext, O extends RouteOptions> =
{ readonly [K in keyof C]: K extends 'request' ? any : C[K] } & (O['body'] extends Schema<infer T> ? { body: T } : {});
type RouteHandler<C extends BaseContext, O extends RouteOptions> = (context: SpecifyContext<C, O>) => any;
class Mini {
get<const O extends RouteOptions>(path: string, handler: RouteHandler<BaseContext, O>, options?: O): Mini { return this; }
}
/* Mini.get<RouteOptions> */
const mini = new Mini();
mini.get('/example', ctx => ctx.body, // <-- Error here
{
body: s,
middleware: [(ctx, next) => next()],
} as const,
);
/* Mini.get<{ readonly body: Schema<{ hello: string; }, { hello: string; }>; }> */
mini.get('/example', ctx => ctx.body, { body: s } as const,);