Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add getStaticPaths type helpers to infer params and props #6150

Merged
merged 3 commits into from
Mar 6, 2023
Merged
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
5 changes: 5 additions & 0 deletions .changeset/flat-candles-glow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': minor
---

Add getStaticPaths type helpers to infer params and props
54 changes: 54 additions & 0 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1092,6 +1092,60 @@ export type GetStaticPaths = (
| GetStaticPathsResult
| GetStaticPathsResult[];

/**
* Infers the shape of the `params` property returned by `getStaticPaths()`.
*
* @example
* ```ts
* export async function getStaticPaths() {
* return results.map((entry) => ({
* params: { slug: entry.slug },
* }));
* }
*
* type Params = InferGetStaticParamsType<typeof getStaticPaths>;
* // ^? { slug: string; }
*
* const { slug } = Astro.params as Params;
* ```
*/
export type InferGetStaticParamsType<T> = T extends () => Promise<infer R>
? R extends Array<infer U>
? U extends { params: infer P }
? P
: never
: never
: never;

/**
* Infers the shape of the `props` property returned by `getStaticPaths()`.
*
* @example
* ```ts
* export async function getStaticPaths() {
* return results.map((entry) => ({
* params: { slug: entry.slug },
* props: {
* propA: true,
* propB: 42
* },
* }));
* }
*
* type Props = InferGetStaticPropsType<typeof getStaticPaths>;
* // ^? { propA: boolean; propB: number; }
*
* const { propA, propB } = Astro.props as Props;
* ```
*/
export type InferGetStaticPropsType<T> = T extends () => Promise<infer R>
? R extends Array<infer U>
? U extends { props: infer P }
? P
: never
: never
: never;

export interface HydrateOptions {
name: string;
value?: string;
Expand Down