In svelte (or sveltekit?) you can define a base +layout.ts
file with a load
function. The data returned from this function is seemingly accessible to all +page.svelte
and +layout.svelte
files as data
. However I cannot figure out how to provide typing for this using Typescript.
Example
+layout.ts
// Return a "user" from the load function
export interface User {
name: string,
id: number
};
export const load = async () => {
return {
name: "User",
id: 123
}
}
Example of a +layout.svelte
file
<script lang="ts">
// What should this be typed as?
// Sure it could be "User" but it seems svelte wants you to use generated typings?
// Like LayoutData or PageData?
export let data;
</script>
<div>
Hello {data.name}
</div>
Provided you have a somewhat recent version of the svelte language server and typescript plugin, they automatically type everything for you in this situation.
To type load
and data
correctly, you may need information about the directory structure (as SvelteKit operates with directory-based routes) and the file name (+page
, +layout
, +server
...). SvelteKit used to just generate the correct types in ./$types
, leaving to the developer the task of annotating.
However, as of March 9th, SvelteKit introduced a new feature: Zero-effort type safety. it now automatically inserts the correct type. I highly recommend you check out the announcement post, it even shows an example on the old way to type load
and data
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With