diff options
author | 2023-03-06 17:38:42 +0100 | |
---|---|---|
committer | 2023-03-06 11:38:42 -0500 | |
commit | b087b83fe266c431fe34a07d5c2293cc4ab011c6 (patch) | |
tree | 565799036fd7a24a1307b8dc9f19d53bc70b2770 | |
parent | 19fe4cb6299d723ad286c4adf766ba8cd41461b4 (diff) | |
download | astro-b087b83fe266c431fe34a07d5c2293cc4ab011c6.tar.gz astro-b087b83fe266c431fe34a07d5c2293cc4ab011c6.tar.zst astro-b087b83fe266c431fe34a07d5c2293cc4ab011c6.zip |
Add getStaticPaths type helpers to infer params and props (#6150)
* feat(astro): add InferGetStaticParamsType and InferGetStaticPropsType type helpers
* chore(astro): added changeset
-rw-r--r-- | .changeset/flat-candles-glow.md | 5 | ||||
-rw-r--r-- | packages/astro/src/@types/astro.ts | 54 |
2 files changed, 59 insertions, 0 deletions
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<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; |