Задать вопрос
@SVAY

Неверное сворачивание типов TypeScript?

При использование middleware типизация body исчезает и появляется ошибка. Без него ошибки не наблюдается, я полагаю TypeScript сворачивает типы в более общий интерфейс и затем body отбрасывается, но почему это происходит мне не понятно. Что бы словить ошибку нужно раскомментить строку с middleware. TS Playground
import type { BunRequest } from 'bun';
import type { Schema } from 'sury';
import { schema } from 'sury';

interface BaseContext<P extends string = string> {
  readonly request: BunRequest<P>;
}

export type Middleware<C extends BaseContext> = (context: C, next: () => Middleware<C>) => any | Promise<any>;

interface RouteOptions<P extends string, C extends BaseContext<P>> {
  readonly body?: Schema<any>;
  readonly middleware?: Middleware<C>[];
}

type SpecifyContext<
  P extends string,
  C extends BaseContext<P>,
  O extends RouteOptions<P, C>,
> = {
  readonly [K in keyof C]: K extends 'request' ? BunRequest<P> : C[K];
}
& (O['body'] extends Schema<infer T> ? { body: T } : { });

type RouteHandler<
  P extends string,
  C extends BaseContext<P>,
  O extends RouteOptions<P, C>,
> = (context: SpecifyContext<P, C, O>) => any | Promise<any>;

class Mini<
  Routes = {},
  Context extends BaseContext = BaseContext,
> {
  get<
    const Path extends string,
    const Options extends RouteOptions<Path, Context>,
  >(path: Path,
    handler: RouteHandler<Path, Context, Options>,
    options?: Options,
  ): Mini<Routes & {
    [K in Path]: {
      GET: RouteHandler<Path, Context, Options>;
    }
  }, Context> {
    return this;
  }
}

const mini = new Mini();
mini.get(
  '/example',
  ctx => ctx.body,  // <-- Error here
  {
    body: schema({ hello: 'world' }),
    // middleware: [(ctx, next) => next()], // <-- Uncomment for error
  } as const,
);
  • Вопрос задан
  • 63 просмотра
Подписаться 2 Средний Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы