Skip to content
Myr

fix(types): fix middleware union type merging in MergeMiddlewareResponse (#4602)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* fix(types): fix middleware union type merging in MergeMiddlewareResponse * ci: apply automated fixes * specify `fetch` as app.request ---------

authored by Yusuke Wada · committed by GitHub · parent 6ca01ec · Browse files · 2 files+30 added−4 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>

Diff stats

2 files+30 added−4 removed

  • tests:+24 added−0 removed
  • other:+6 added−4 removed

2 files+30 added−4 removed

modified:src/types.test.ts+24 added
2847 unmodified lines
2848 }2849 })2850 })28512852 describe('Middleware returning union type (undefined | TypedResponse)', () => {2853 test('middleware that conditionally returns response should merge types', async () => {2854 const middleware = createMiddleware(async (c, next) => {2855 if (Math.random() > 0.5) {2856 return c.json({ cause: 'Unauthorized' }, 401)2857 }2858 await next()2859 })28602861 const app = new Hono().get('/test', middleware, (c) => c.json({ message: 'Hello' }, 200))2862 const client = hc<typeof app>('http://localhost', {2863 fetch: app.request,2864 })2865 const res = await client.test.$get()28662867 if (res.status === 200) {2868 expectTypeOf(await res.json()).toEqualTypeOf<{ message: string }>()2869 }2870 if (res.status === 401) {2871 expectTypeOf(await res.json()).toEqualTypeOf<{ cause: string }>()2872 }2873 })2874 })28752876 describe('Merge responses from multiple handlers, no path pattern', () => {2877 test('merge responses from 1 middleware', async () => {2878 const middleware = createMiddleware(async (c) => c.json({ '400': true }, 400))2879
805 unmodified lines
modified:src/types.ts+6 added-4 removed
2366 unmodified lines
2367 : T extends TypedResponse2368 ? T2369 : TypedResponse23702371type ExtractTypedResponseOnly<T> = T extends TypedResponse ? T : never23722373type MergeMiddlewareResponse<T> = T extends (c: any, next: any) => Promise<infer R>2374 ? Exclude<R, void> extends never2375 ? never2374 : Exclude<R, void> extends TypedResponse2375 ? Exclude<R, void>2376 : Exclude<R, void> extends Response | TypedResponse<any, any, any>2377 ? ExtractTypedResponseOnly<Exclude<R, void>>2378 : never2379 : T extends (c: any, next: any) => infer R2378 ? R extends TypedResponse2379 ? R2380 ? R extends Response | TypedResponse<any, any, any>2381 ? ExtractTypedResponseOnly<R>2382 : never2383 : never23842385////////////////////////////////////////
104 unmodified lines