Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining types for svelte and sveltekit layout data

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>

like image 753
radop33392 Avatar asked Sep 06 '25 21:09

radop33392


1 Answers

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.

like image 169
CarlosGDCJ Avatar answered Sep 11 '25 04:09

CarlosGDCJ