Skip to content
This repository was archived by the owner on Jan 11, 2023. It is now read-only.

Commit 19d7eef

Browse files
authored
Add TypeScript types for the preload function (#1468)
1 parent 43fd91b commit 19d7eef

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

runtime/index.d.ts

+21
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
declare module "@sapper/app"
22
declare module "@sapper/server"
33
declare module "@sapper/service-worker"
4+
declare module "@sapper/common"
45

56
declare module "@sapper/app" {
67
export interface Redirect {
@@ -35,3 +36,23 @@ declare module "@sapper/service-worker" {
3536
export const shell: string[];
3637
export const routes: Array<{ pattern: RegExp }>;
3738
}
39+
40+
declare module "@sapper/common" {
41+
export interface PreloadContext {
42+
fetch: (url: string, options?: any) => Promise<any>;
43+
error: (statusCode: number, message: Error | string) => void;
44+
redirect: (statusCode: number, location: string) => void;
45+
}
46+
47+
export interface Page {
48+
host: string;
49+
path: string;
50+
params: Record<string, string>;
51+
query: Record<string, string | string[]>;
52+
error?: Error;
53+
}
54+
55+
export interface Preload {
56+
(this: PreloadContext, page: Page, session: any): object | Promise<object>;
57+
}
58+
}

site/content/docs/04-preloading.md

+20
Original file line numberDiff line numberDiff line change
@@ -122,3 +122,23 @@ You can abort rendering and redirect to a different location with `this.redirect
122122
}
123123
</script>
124124
```
125+
126+
#### Typing the function
127+
128+
If you use TypeScript and want to access the above context methods, TypeScript will thow an error and tell you that it does not know the type of `this`. To fix it, you need to specify the type of `this` (see the [official TypeScript documentation](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#specifying-the-type-of-this-for-functions)). We provide you with helper interfaces so you can type the function like this:
129+
130+
```html
131+
<script context="module">
132+
import type { Page, PreloadContext } from "@sapper/common";
133+
134+
export const preload: Preload = async function(this, page, session) {
135+
const { user } = session;
136+
137+
if (!user) {
138+
return this.redirect(302, 'login'); // TypeScript will know the type of `this` now
139+
}
140+
141+
return { user };
142+
}
143+
</script>
144+
```

0 commit comments

Comments
 (0)