Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix type argument inference of session.get(key) and session.set(key, value) #249

Merged
merged 2 commits into from
May 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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'))
})