From b087b83fe266c431fe34a07d5c2293cc4ab011c6 Mon Sep 17 00:00:00 2001 From: Dennis Morello Date: Mon, 6 Mar 2023 17:38:42 +0100 Subject: [PATCH] Add getStaticPaths type helpers to infer params and props (#6150) * feat(astro): add InferGetStaticParamsType and InferGetStaticPropsType type helpers * chore(astro): added changeset --- .changeset/flat-candles-glow.md | 5 +++ packages/astro/src/@types/astro.ts | 54 ++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 .changeset/flat-candles-glow.md diff --git a/.changeset/flat-candles-glow.md b/.changeset/flat-candles-glow.md new file mode 100644 index 000000000..75d69f51e --- /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 199250d21..c915da2ec 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;