Skip to content
Open
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
24 changes: 23 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1034,6 +1034,23 @@ type MergeFlattenMacroResponse<A, B> = {
? B[K]
: never
}

type UnionKeys<T> = T extends unknown ? keyof T : never

type UnionValue<T, K extends PropertyKey> = T extends unknown
? K extends keyof T
? T[K]
: never
: never

type MergeObjectUnion<T> = [T] extends [object]
? Prettify<
{
[K in UnionKeys<T>]: UnionValue<T, K>
}
>
: T

type UnionMacroContext<A> = UnionToIntersect<{
[K in Exclude<keyof A, 'return'>]: A[K]
}> & {
Expand All @@ -1054,7 +1071,12 @@ export type MacroToContext<
R
> extends infer A
? {
[K in Exclude<keyof A, 'return'>]: UnionToIntersect<A[K]>
[K in Exclude<
keyof A,
'return'
>]: K extends 'resolve'
? MergeObjectUnion<A[K]>
: UnionToIntersect<A[K]>
} & Prettify<{
// @ts-ignore
return: FlattenMacroResponse<A['return']>
Expand Down
38 changes: 38 additions & 0 deletions test/types/macro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,44 @@ import { expectTypeOf } from 'expect-type'
)
}

// resolve union of object shapes preserves shared context
{
const plugin = new Elysia({ name: 'plugin' }).macro({
withUser: {
resolve() {
if (Math.random() > 0.5)
return {
user: {
id: 'a'
}
}

return {
user: {
id: 'b'
},
admin: true
}
}
}
})

new Elysia()
.use(plugin)
.get(
'/',
({ user, admin }) => {
expectTypeOf(user).toEqualTypeOf<{ id: string }>()
expectTypeOf(admin).toEqualTypeOf<boolean | undefined>()

return user.id
},
{
withUser: true
}
)
}

// resolve with custom status
{
const app = new Elysia()
Expand Down