From dfe5aaf16f47870945319b83641d8664d767e2c8 Mon Sep 17 00:00:00 2001 From: Cesar Canassa Date: Tue, 15 Oct 2024 22:14:33 +0200 Subject: [PATCH] :label: ensures that handler return is properly typed - This change addresses an issue where the return type of handlers was not being correctly enforced by the TypeScript compiler. As far as I could tell, the issue is caused by the `infer` keyword not working with generic types. - Added `TResult` as a type parameter to `MiddlewareHandler` to explicitly specify the handler's return type. - Modified the `middy` function signature to pass `TResult` to `MiddlewareHandler`. - By explicitly specifying `TResult`, we ensure that the compiler can correctly enforce the handler's return type. closes #1228 --- packages/core/index.d.ts | 9 +++++---- packages/core/index.test-d.ts | 17 ++++++++++++++++- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/packages/core/index.d.ts b/packages/core/index.d.ts index cf0a0c78b..375890e5c 100644 --- a/packages/core/index.d.ts +++ b/packages/core/index.d.ts @@ -99,7 +99,7 @@ export interface MiddyfiedHandler< handler: ( handler: MiddlewareHandler< LambdaHandler, - TContext + TContext, TResult > ) => MiddyfiedHandler } @@ -150,8 +150,9 @@ infer TMiddlewareInternal declare type MiddlewareHandler< THandler extends LambdaHandler, - TContext extends LambdaContext = LambdaContext -> = THandler extends LambdaHandler // always true + TContext extends LambdaContext = LambdaContext, + TResult = any +> = THandler extends LambdaHandler // always true ? MiddyInputHandler : never @@ -169,7 +170,7 @@ declare function middy< > ( handler?: | LambdaHandler - | MiddlewareHandler, TContext> + | MiddlewareHandler, TContext, TResult> | PluginObject, plugin?: PluginObject ): MiddyfiedHandler diff --git a/packages/core/index.test-d.ts b/packages/core/index.test-d.ts index bec0f5c09..2680f7f28 100644 --- a/packages/core/index.test-d.ts +++ b/packages/core/index.test-d.ts @@ -408,4 +408,19 @@ const s3Handler = async (event: S3Event): Promise => { } const handler1182 = middy().handler(s3Handler) -expectType>(handler1182) +expectType>(handler1182) + +// Issue #1228 Correct return type +const numberHandler = middy() + .handler(async (event) => { + return 42 // Correct return type, should pass type checking + }) +expectType>(numberHandler) + +// Issue #1228 Incorrect return type +const invalidNumberHandler = middy() + // @ts-expect-error + .handler(async () => { + return 'not a number' + }) +expectType>(invalidNumberHandler)