Skip to content

No typings for ctx and env? #1

@davej

Description

@davej

This is an awesome lib and I'm getting a ton of value from it. I find myself having to jump through hoops to get things typed properly though. Perhaps I am doing things wrong?

Here is an example of how I'm trying to create a new typedParams middleware to add a downloadParams object. And also adding typings for ctx and env (because otherwise they are any type). Is there a better way to do this?

interface DownloadParams {
  appId?: string;
  appVersion?: string;
}

interface Env {
  R2_BUCKET: R2Bucket;
  ORIGIN_URL: string;
  ENVIRONMENT: "dev" | "prod";
}


type AddCtxAndEnvType<T> = Omit<T, "ctx" | "env"> & {
  ctx?: ExecutionContext;
  env?: Env;
};

type Awaitable<T> = T | PromiseLike<T>;
type TypedMiddleware<T extends (...args) => any> = Handler<
  Awaited<ReturnType<T>> & RouteContext
>;
const typedParams =
  () =>
  async <X extends BasicsContext>(
    ax: Awaitable<X>
  ): Promise<X & { downloadParams?: DownloadParams }> => {
    const x = await ax;
    return Object.assign(x, { downloadParams: x.params as DownloadParams });
  };

const middleware = combine(basics(), typedParams());

const handler: TypedMiddlware<typeof middleware> = async (
  req,
  {
    downloadParams,
    userAgent,
    env,
    ctx,
    waitUntil,
    url,
  }: AddCtxAndEnvType<Parameters<TypedMiddleware<typeof middleware>>[1]>
): Promise<Response> => {
  // ...
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions