@@ -378,4 +378,64 @@ describe('JwtService', () => {
378
378
) ;
379
379
} ) ;
380
380
} ) ;
381
+
382
+ describe ( 'should properly handle generic types' , ( ) => {
383
+ let jwtService : JwtService ;
384
+
385
+ // Define an interface for type safety testing
386
+ interface UserPayload {
387
+ id : number ;
388
+ username : string ;
389
+ roles : string [ ] ;
390
+ }
391
+
392
+ beforeAll ( async ( ) => {
393
+ jwtService = await setup ( { secretOrKeyProvider : undefined } ) ;
394
+ } ) ;
395
+
396
+ it ( 'should sign with correct interface implementation' , ( ) => {
397
+ const validPayload : UserPayload = {
398
+ id : 1 ,
399
+ username : 'testuser' ,
400
+ roles : [ 'user' , 'admin' ]
401
+ } ;
402
+
403
+ // This should pass type checking
404
+ const token = jwtService . sign < UserPayload > ( validPayload ) ;
405
+ expect ( token ) . toBeDefined ( ) ;
406
+ } ) ;
407
+
408
+ it ( 'should fail type checking with incorrect interface implementation' , ( ) => {
409
+ const invalidPayload = {
410
+ id : 1 ,
411
+ // Missing username property
412
+ roles : [ 'user' ]
413
+ } ;
414
+
415
+ // @ts -expect-error as the username property is not defined in the payload
416
+ jwtService . sign < UserPayload > ( invalidPayload ) ;
417
+ } ) ;
418
+
419
+ it ( 'should signAsync with correct interface implementation' , async ( ) => {
420
+ const validPayload : UserPayload = {
421
+ id : 1 ,
422
+ username : 'testuser' ,
423
+ roles : [ 'user' , 'admin' ]
424
+ } ;
425
+
426
+ const token = await jwtService . signAsync < UserPayload > ( validPayload ) ;
427
+ expect ( token ) . toBeDefined ( ) ;
428
+ } ) ;
429
+
430
+ it ( 'should fail type checking with incorrect interface implementation for signAsync' , async ( ) => {
431
+ const invalidPayload = {
432
+ id : 1 ,
433
+ // Missing username property
434
+ roles : [ 'user' ]
435
+ } ;
436
+
437
+ // @ts -expect-error as the username property is not defined in the payload
438
+ await jwtService . signAsync < UserPayload > ( invalidPayload ) ;
439
+ } ) ;
440
+ } ) ;
381
441
} ) ;
0 commit comments