In Sveltekit, I'm using the load function to call an API. I want to use the Fetch that is passed to the load function - but I'm using Typescript.
Where's the type for fetch/params/ etc?
/** @type {import('./$types').PageLoad} */
export async function load ({fetch}) {
const rndInt = randomIntFromInterval(1, 20)
const res = await fetch(`https://jsonplaceholder.typicode.com/todos/${rndInt}`)
item = await res.json();
return {item}
}
CodePudding user response:
This is just a matter of applying the type to the load function, it does not matter where its component parts are defined. The only important thing is that ./$types
will be generated by the dev server which has to be running to update correctly.
To apply the type to a function, it is easiest to define it as a const
:
export const load: PageLoad = ({ fetch }) => {
// fetch will have the correct type here automatically
}
The automatically generated types are in .svelte-kit/types/src/routes/...
, the hierarchy will mirror the routes
directory with the actual sources, which allows for the ./$types
import.
(The base types are defined in the @sveltejs/kit
package, see node_modules\@sveltejs/kit/types/index.d.ts
. If your editor supports a "Go to definition" command, you can just navigate using that. Invoke it on PageLoad
and/or Kit.Load
and just have a look around.)