Skip to content

Commit

Permalink
Fix type argument inference of session.get(key) and `session.set(ke…
Browse files Browse the repository at this point in the history
…y, value)` (#249)

* Update types.d.ts

Signed-off-by: Raku Zeta <zetaraku@gmail.com>

* Update types.test-d.ts

Signed-off-by: Raku Zeta <zetaraku@gmail.com>

---------

Signed-off-by: Raku Zeta <zetaraku@gmail.com>
  • Loading branch information
zetaraku committed May 7, 2024
1 parent b42ab14 commit 90ee1f5
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
4 changes: 2 additions & 2 deletions types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,10 @@ declare namespace fastifySession {
save(): Promise<void>;

/** sets values in the session. */
set<K extends keyof Fastify.Session, V = Fastify.Session[K]>(key: K, value: V): void;
set<K extends keyof Fastify.Session>(key: K, value: Fastify.Session[K]): void;

/** gets values from the session. */
get<K extends keyof Fastify.Session, V = Fastify.Session[K] | undefined>(key: K): V;
get<K extends keyof Fastify.Session>(key: K): Fastify.Session[K] | undefined;

/** checks if session has been modified since it was generated or loaded from the store. */
isModified(): boolean;
Expand Down
12 changes: 9 additions & 3 deletions types/types.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ app.route({
expectType<{ id: number } | undefined>(session?.user);
});
expectType<void>(request.session.set('foo', 'bar'));
expectType<string>(request.session.get<'foo', string>('foo'));
expectType<string | undefined>(request.session.get('foo'));
expectType<void>(request.session.touch());
expectType<boolean>(request.session.isModified());
expectType<void>(request.session.reload(() => {}));
Expand Down Expand Up @@ -144,12 +144,18 @@ const app2 = fastify()
app2.register(fastifySession)

app2.get('/', async function(request) {
let num: number | undefined, str: string | undefined;
expectError(num = request.session.get('foo'));
expectAssignable(str = request.session.get('foo'));
expectError(request.session.set('foo', 2));
expectAssignable(request.session.set('foo', 'bar'));

expectType<undefined | { id: number }>(request.session.get('user'))
expectAssignable(request.session.set('user', { id: 2 }))

expectError(request.session.get('not exist'))
expectError(request.session.set('not exist', 'abc'))

expectType<'bar'>(request.session.get<any, 'bar'>('not exist'))
expectAssignable(request.session.set<any, string>('not exist', 'abc'))
expectType<any>(request.session.get<any>('not exist'))
expectAssignable(request.session.set<any>('not exist', 'abc'))
})

0 comments on commit 90ee1f5

Please sign in to comment.