Skip to content

Commit

Permalink
feat(svelte2tsx): autotype const load = ... declarations (#2540)
Browse files Browse the repository at this point in the history
  • Loading branch information
GauBen authored Oct 31, 2024
1 parent 7c23767 commit 77c9ccf
Show file tree
Hide file tree
Showing 6 changed files with 56 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export interface PageLoadEvent<> {
test: {
exists: boolean;
};
}

export type PageLoad<OutputData = Record<string, any>> = (event: PageLoadEvent) => OutputData;

export type PageData = ReturnType<typeof import('./+page').load>;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<script lang="ts">
export let data;
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// In a real SvelteKit application, $types are autogenerated, for this test we manually create them to our liking
// @ts-expect-error - to silence tsc
export const load = decorator((event) => event.test);

// Dummy decorator function, to open the door to SvelteKit extensions
function decorator<T>(fn: T): T {
return fn;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[
{
"range": {
"start": {
"line": 4,
"character": 1
},
"end": {
"line": 4,
"character": 5
}
},
"severity": 1,
"source": "ts",
"message": "Property 'data' is missing in type '{}' but required in type '{ data: { exists: boolean; }; }'.",
"code": 2741,
"tags": []
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<script lang="ts">
import Page from './+page.svelte';
</script>

<Page />
12 changes: 12 additions & 0 deletions packages/svelte2tsx/src/helpers/sveltekit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,18 @@ function upsertKitRouteFile(
);

insert(pos, inserted);
} else if (load?.type === 'var' && !load.hasTypeDefinition) {
// "const load = ..." will be transformed into
// "const load = (...) satisfies PageLoad"
insert(load.node.initializer.getStart(), surround('('));
insert(
load.node.initializer.getEnd(),
surround(
`) satisfies import('./$types.js').${basename.includes('layout') ? 'Layout' : 'Page'}${
basename.includes('server') ? 'Server' : ''
}Load`
)
);
}

// add type to entries function if not explicitly typed
Expand Down

0 comments on commit 77c9ccf

Please sign in to comment.