Skip to content

Commit 77c9ccf

Browse files
authored
feat(svelte2tsx): autotype const load = ... declarations (#2540)
1 parent 7c23767 commit 77c9ccf

File tree

6 files changed

+56
-0
lines changed

6 files changed

+56
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
export interface PageLoadEvent<> {
2+
test: {
3+
exists: boolean;
4+
};
5+
}
6+
7+
export type PageLoad<OutputData = Record<string, any>> = (event: PageLoadEvent) => OutputData;
8+
9+
export type PageData = ReturnType<typeof import('./+page').load>;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
<script lang="ts">
2+
export let data;
3+
</script>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// In a real SvelteKit application, $types are autogenerated, for this test we manually create them to our liking
2+
// @ts-expect-error - to silence tsc
3+
export const load = decorator((event) => event.test);
4+
5+
// Dummy decorator function, to open the door to SvelteKit extensions
6+
function decorator<T>(fn: T): T {
7+
return fn;
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
[
2+
{
3+
"range": {
4+
"start": {
5+
"line": 4,
6+
"character": 1
7+
},
8+
"end": {
9+
"line": 4,
10+
"character": 5
11+
}
12+
},
13+
"severity": 1,
14+
"source": "ts",
15+
"message": "Property 'data' is missing in type '{}' but required in type '{ data: { exists: boolean; }; }'.",
16+
"code": 2741,
17+
"tags": []
18+
}
19+
]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<script lang="ts">
2+
import Page from './+page.svelte';
3+
</script>
4+
5+
<Page />

packages/svelte2tsx/src/helpers/sveltekit.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,18 @@ function upsertKitRouteFile(
160160
);
161161

162162
insert(pos, inserted);
163+
} else if (load?.type === 'var' && !load.hasTypeDefinition) {
164+
// "const load = ..." will be transformed into
165+
// "const load = (...) satisfies PageLoad"
166+
insert(load.node.initializer.getStart(), surround('('));
167+
insert(
168+
load.node.initializer.getEnd(),
169+
surround(
170+
`) satisfies import('./$types.js').${basename.includes('layout') ? 'Layout' : 'Page'}${
171+
basename.includes('server') ? 'Server' : ''
172+
}Load`
173+
)
174+
);
163175
}
164176

165177
// add type to entries function if not explicitly typed

0 commit comments

Comments
 (0)