cloudflare / cloudflare/workerd

Improve type for Params in PagesFunction and EventContext

Open
#679 0 comments 1 reaction 1 assignee Claimed by @workers-devprod View on GitHub
types
Dominant language
C++
Stars
8.7k
Forks
739
Avg merge
2d 20h
Merged PRs (30d)
174

Description

Currently the EventContext, and by extension PagesFunction, accept a union of param keys, `PagesFunction`, which produces a `params` record that contains all the keys with type `string | string[]`. This is annoying to use, since the author of the function knows, based on the path, if each param is a `string` or `string[]`.

Given the path of the function we can determine correct for each param, using the following TypeScript types:

```ts
type Param = T extends `[[${infer N}]]`
? Record
: T extends `[${infer N}]`
? Record
: {};

type Params = S extends `${infer T}/${infer R}`
? Readonly & Param>
: Param;

declare type EventContext = {
// ...
params: Params

;
};

// then in the code:
export const onRequest: PagesFunction = async ({ params }) => {
// params is now typed as {slug: string[], id: string}
});
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.