koajs / generic-session

koa session store with memory, redis or others.
MIT License
414 stars 65 forks source link

[fix] Context TS typing is not working #142

Open QuentinRoy opened 1 year ago

QuentinRoy commented 1 year ago

Describe the bug

Node.js version: 18.12.1

Typescript version: 4.9.4

Koa version: 2.14.1 (types: 2.13.5)

OS version: Mac OS 13.0.1

Description: Context's session is not properly typed despite the type definitions.

Actual behavior

declare module "koa-generic-session" {
  interface Session {
    foo: "bar";
  }
}

app.use((ctx) => {
  // session is any.
  let { session } = ctx;
  // This is fine.
  session.cookie = "hahahaha !";
  // foo is any
  let foo = session.foo;
});

Expected behavior

declare module "koa-generic-session" {
  interface Session {
    foo: "bar";
  }
}

app.use((ctx) => {
  // session is Session.
  let { session } = ctx;
  // The line below is a type error.
  // session.cookie = "hahahaha !";
  // foo is "bar"
  let foo = session.foo;
});

Code to reproduce

main.ts

import koa from "koa";
import session, { Session } from "koa-generic-session";

let store: Record<string, Session> = {};

declare module "koa-generic-session" {
  interface Session {
    foo: "bar";
  }
}

const app = new koa();
app.use(
  session({
    store: {
      get(key: string) {
        return store[key];
      },
      set(key: string, sess: Session) {
        store[key] = sess;
      },
      destroy(key: string) {
        delete store[key];
      },
    },
  }),
);

app.use((ctx) => {
  // session is any but should be Session.
  let { session } = ctx;
  // This is fine but shouldn't.
  session.cookie = "hahahaha !";
  // foo is any but should be "bar".
  let foo = session.foo;
});

app.listen(8080);

package.json

{
  "name": "ts-koa-session",
  "version": "1.0.0",
  "dependencies": {
    "@types/koa": "^2.13.5",
    "@types/koa-generic-session": "^2.2.1",
    "koa": "^2.14.1",
    "koa-generic-session": "^2.3.0",
    "typescript": "^4.9.4"
  }
}

tsconfig.json

{
  "$schema": "https://json.schemastore.org/tsconfig",
  "compilerOptions": {
    "esModuleInterop": true
  }
}

Checklist

Potential fix or workaround

At the moment, I need to manually define the context type for my app:

const app = new koa<DefaultState, Context>();

Is this the intended use?

titanism commented 1 year ago

As maintainers we don't write nor support TS, but a PR is welcome!

QuentinRoy commented 1 year ago

Thanks for the answer! This makes sense. Unfortunately, I am afraid I won't be able to work on this myself, at least in the time being. Just to clarify, you are talking about a PR to https://github.com/DefinitelyTyped/DefinitelyTyped, is it?

titanism commented 1 year ago

I think (?) not sure though!