Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(svelte2tsx): autotype const load = ... declarations #2540

Merged
merged 1 commit into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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