How do I fix this TypeScript issue with Koa Session using a Koa App that is generically typed?
Asked Answered
P

0

6

I'm using the following interfaces to define my context & state for koa:

export interface AppState extends Koa.DefaultState {
  //...
}
export interface AppContext extends Koa.DefaultContext {
  models: DomainModels;
  connection: Connection;
}

and then instantiate koa as such:

const app = new Koa<AppState, AppContext>();
app.use(session(sessionConfig, app));

The problem is that the types for koa-session use declaration merging and are causing the following error:

Argument of type 'import("/Users/chance/Projects/pear/packages/api/node_modules/@types/koa/index.d.ts")<AppState, AppContext>' is not assignable to parameter of type 'import("/Users/chance/Projects/pear/packages/api/node_modules/@types/koa/index.d.ts")<DefaultState, DefaultContext>'.
  Types of property 'middleware' are incompatible.
    Type 'Middleware<ParameterizedContext<AppState, AppContext>>[]' is not assignable to type 'Middleware<ParameterizedContext<DefaultState, DefaultContext>>[]'.
      Type 'Middleware<ParameterizedContext<AppState, AppContext>>' is not assignable to type 'Middleware<ParameterizedContext<DefaultState, DefaultContext>>'.
        Type 'ParameterizedContext<DefaultState, DefaultContext>' is not assignable to type 'ParameterizedContext<AppState, AppContext>'.
          Type 'ExtendableContext & { state: DefaultState; } & DefaultContext' is missing the following properties from type 'AppContext': models, connection, session, sessionOptionsts(2345)

The relevant parts from @types/koa-session:

declare function session(CONFIG: Partial<session.opts>, app: Koa): Koa.Middleware;

declare function session(app: Koa): Koa.Middleware

declare module "koa" {
    interface Context {
        session: session.Session | null;
        readonly sessionOptions: session.opts | undefined;
    }
}
Plentiful answered 9/5, 2020 at 3:0 Comment(2)
could you please provide an update on how you dealt with this ?Antoineantoinetta
An ugly workaround is retyping the app in the call like app.use(session(app as unknown as Koa)) but I really hope there is a better option.Wentz

© 2022 - 2024 — McMap. All rights reserved.