mirror of
https://github.com/withastro/astro.git
synced 2025-01-27 22:19:04 -05:00
feat: ActionReturnType
(#11443)
* feat: ActionReturnType util * feat(test): ActionReturnType * chore: changeset
This commit is contained in:
parent
7dca68ff2e
commit
ea4bc04e94
3 changed files with 49 additions and 0 deletions
29
.changeset/small-vans-own.md
Normal file
29
.changeset/small-vans-own.md
Normal file
|
@ -0,0 +1,29 @@
|
|||
---
|
||||
'astro': patch
|
||||
---
|
||||
|
||||
Expose new `ActionReturnType` utility from `astro:actions`. This infers the return type of an action by passing `typeof actions.name` as a type argument. This example defines a `like` action that returns `likes` as an object:
|
||||
|
||||
```ts
|
||||
// actions/index.ts
|
||||
import { defineAction } from 'astro:actions';
|
||||
|
||||
export const server = {
|
||||
like: defineAction({
|
||||
handler: () => {
|
||||
/* ... */
|
||||
return { likes: 42 }
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
In your client code, you can infer this handler return value with `ActionReturnType`:
|
||||
|
||||
```ts
|
||||
// client.ts
|
||||
import { actions, ActionReturnType } from 'astro:actions';
|
||||
|
||||
type LikesResult = ActionReturnType<typeof actions.like>;
|
||||
// -> { likes: number }
|
||||
```
|
|
@ -19,6 +19,8 @@ type Handler<TInputSchema, TOutput> = TInputSchema extends z.ZodType
|
|||
? (input: z.infer<TInputSchema>, context: ActionAPIContext) => MaybePromise<TOutput>
|
||||
: (input: any, context: ActionAPIContext) => MaybePromise<TOutput>;
|
||||
|
||||
export type ActionReturnType<T extends Handler<any, any>> = Awaited<ReturnType<T>>;
|
||||
|
||||
export type ActionClient<
|
||||
TOutput,
|
||||
TAccept extends Accept | undefined,
|
||||
|
|
18
packages/astro/test/types/action-return-type.ts
Normal file
18
packages/astro/test/types/action-return-type.ts
Normal file
|
@ -0,0 +1,18 @@
|
|||
import { describe, it } from 'node:test';
|
||||
import { expectTypeOf } from 'expect-type';
|
||||
import { type ActionReturnType, defineAction } from '../../dist/actions/runtime/virtual/server.js';
|
||||
import { z } from '../../zod.mjs';
|
||||
|
||||
describe('ActionReturnType', () => {
|
||||
it('Infers action return type', async () => {
|
||||
const action = defineAction({
|
||||
input: z.object({
|
||||
name: z.string(),
|
||||
}),
|
||||
handler: async ({ name }) => {
|
||||
return { name };
|
||||
},
|
||||
});
|
||||
expectTypeOf<ActionReturnType<typeof action>>().toEqualTypeOf<{ name: string }>();
|
||||
});
|
||||
});
|
Loading…
Add table
Reference in a new issue