0
Fork 0
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:
Ben Holmes 2024-07-10 07:05:13 -04:00 committed by GitHub
parent 7dca68ff2e
commit ea4bc04e94
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 49 additions and 0 deletions

View 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 }
```

View file

@ -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,

View 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 }>();
});
});