diff --git a/.changeset/flat-candles-glow.md b/.changeset/flat-candles-glow.md new file mode 100644 index 000000000000..75d69f51e4ed --- /dev/null +++ b/.changeset/flat-candles-glow.md @@ -0,0 +1,5 @@ +--- +'astro': minor +--- + +Add getStaticPaths type helpers to infer params and props diff --git a/packages/astro/src/@types/astro.ts b/packages/astro/src/@types/astro.ts index 199250d21efa..c915da2ec87f 100644 --- a/packages/astro/src/@types/astro.ts +++ b/packages/astro/src/@types/astro.ts @@ -1094,6 +1094,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; + * // ^? { slug: string; } + * + * const { slug } = Astro.params as Params; + * ``` + */ +export type InferGetStaticParamsType = T extends () => Promise + ? R extends Array + ? 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; + * // ^? { propA: boolean; propB: number; } + * + * const { propA, propB } = Astro.props as Props; + * ``` + */ +export type InferGetStaticPropsType = T extends () => Promise + ? R extends Array + ? U extends { props: infer P } + ? P + : never + : never + : never; + export interface HydrateOptions { name: string; value?: string;