Skip to content

Commit

Permalink
Merge pull request #1244 from canassa/fix-handler-return-type
Browse files Browse the repository at this point in the history
🏷️ ensures that handler return is properly typed
  • Loading branch information
willfarrell authored Oct 16, 2024
2 parents 4ad95ba + dfe5aaf commit a823417
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
9 changes: 5 additions & 4 deletions packages/core/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export interface MiddyfiedHandler<
handler: <TInputHandlerEventProps = TEvent, TInputHandlerResultProps = TResult>(
handler: MiddlewareHandler<
LambdaHandler<TInputHandlerEventProps, TInputHandlerResultProps>,
TContext
TContext, TResult
>
) => MiddyfiedHandler<TInputHandlerEventProps, TInputHandlerResultProps, TErr, TContext, TInternal>
}
Expand Down Expand Up @@ -150,8 +150,9 @@ infer TMiddlewareInternal

declare type MiddlewareHandler<
THandler extends LambdaHandler<any, any>,
TContext extends LambdaContext = LambdaContext
> = THandler extends LambdaHandler<infer TEvent, infer TResult> // always true
TContext extends LambdaContext = LambdaContext,
TResult = any
> = THandler extends LambdaHandler<infer TEvent, TResult> // always true
? MiddyInputHandler<TEvent, TResult, TContext>
: never

Expand All @@ -169,7 +170,7 @@ declare function middy<
> (
handler?:
| LambdaHandler<TEvent, TResult>
| MiddlewareHandler<LambdaHandler<TEvent, TResult>, TContext>
| MiddlewareHandler<LambdaHandler<TEvent, TResult>, TContext, TResult>
| PluginObject,
plugin?: PluginObject
): MiddyfiedHandler<TEvent, TResult, TErr, TContext, TInternal>
Expand Down
17 changes: 16 additions & 1 deletion packages/core/index.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -408,4 +408,19 @@ const s3Handler = async (event: S3Event): Promise<void> => {
}

const handler1182 = middy().handler(s3Handler)
expectType<MiddyfiedHandler<S3Event, void, Error, Context, {}>>(handler1182)
expectType<MiddyfiedHandler<S3Event, any, Error, Context, {}>>(handler1182)

// Issue #1228 Correct return type
const numberHandler = middy<APIGatewayProxyEvent, number>()
.handler(async (event) => {
return 42 // Correct return type, should pass type checking
})
expectType<middy.MiddyfiedHandler<APIGatewayProxyEvent, number>>(numberHandler)

// Issue #1228 Incorrect return type
const invalidNumberHandler = middy<APIGatewayProxyEvent, number>()
// @ts-expect-error
.handler(async () => {
return 'not a number'
})
expectType<middy.MiddyfiedHandler<APIGatewayProxyEvent, number>>(invalidNumberHandler)

0 comments on commit a823417

Please sign in to comment.