diff --git a/README.md b/README.md index 8ff3bda..4d79740 100644 --- a/README.md +++ b/README.md @@ -331,7 +331,7 @@ fastify.decodeSecureSession(request.cookies['session'], undefined, 'mySecondSess ## Add TypeScript types -The session data is typed as `{ [key: string]: any }`. This can be extended with [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) to get improved type support. +The session data is defined as an interface called `SessionData`. It can be extended with [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) for improved type support. ```ts declare module '@fastify/secure-session' { diff --git a/types/index.d.ts b/types/index.d.ts index f9e30b3..f44c0c1 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -15,6 +15,7 @@ declare module "fastify" { } type FastifySecureSession = FastifyPluginCallback>)[]>; +interface SessionData {} declare namespace fastifySecureSession { export type Session = Partial & { @@ -29,10 +30,6 @@ declare namespace fastifySecureSession { touch(): void; } - export interface SessionData { - [key: string]: any; - } - export type SecureSessionPluginOptions = { cookie?: CookieSerializeOptions cookieName?: string diff --git a/types/index.test-d.ts b/types/index.test-d.ts index 10ab2d9..17a2b72 100644 --- a/types/index.test-d.ts +++ b/types/index.test-d.ts @@ -39,7 +39,6 @@ app.get("/not-websockets", async (request, reply) => { expectType(request.session.get("foo")); expectType(request.session.get("baz")); expectType(request.session.foo); - expectType(request.session.baz); expectType(request.session.data()); request.session.delete(); request.session.options({ maxAge: 42 }) @@ -51,6 +50,13 @@ app.get("/not-websockets", async (request, reply) => { request.foo.delete(); request.foo.options({ maxAge: 42 }); request.foo.touch(); + + // @ts-expect-error: set undefined key + request.session.set("baz", "bar"); + // @ts-expect-error: invoke undefined key + expectType(request.session.baz); + // @ts-expect-error: invoke undefined key + request.baz.touch() }); expectType(app.decodeSecureSession("some cookie"))