generic-session
generic-session copied to clipboard
[fix] Context TS typing is not working
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
- [x] I have searched through GitHub issues for similar issues.
- [x] I have completely read through the README and documentation.
- [x] I have tested my code with the latest version of Node.js and this package and confirmed it is still not working.
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?
As maintainers we don't write nor support TS, but a PR is welcome!
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?
I think (?) not sure though!