Error in preload: Error: Object is possibly 'undefined.'
richarddavenport opened this issue · 5 comments
Trying to use context in the preload function. And I'm getting this error:
I've read a few things describing what's happening, but I'm really not sure how to fix this. Any help would be great!
TypeScript support for preload isn't all the way there yet; see upstream issue sveltejs/language-tools#497.
For right now, [hypothesis:] it may be possible to add a non-null assertion and typecast like this?:
(this!.fetch as typeof fetch)(args)
or maybe with an as any
in the middle to ensure it'll work?:
(this!.fetch as any as typeof fetch)(args)
Just tried that, but I'm getting Error: 'this' implicitly has type 'any' because it does not have a type annotation.
I'm trying everything I can think of to get this
to be typed correctly, but I'm pretty sure what I'm doing will break sapper.
Thanks for upstream issue. Watching that issue now. How are we suppose to use preload in a typescript based sapper application?
Then it's probably closer to correct to do
((this as any).fetch as typeof fetch)(args)
(I hope)
Type it like this:
// Better move that into some file and do `import type { PreloadContext } from ...` to not type it every time
interface PreloadContext {
fetch: ...,
...
}
// won't work with export const preload = (...
export async function preload(this: PreloadContext, ...page/session, if you need it) {
...
this.fetch(...) // <-- works without type errors
}
Thanks @dummdidumm, looks like that fixes the typing issues, appreciate the help!
I'm still having another issue with rollup I think src/routes/index.svelte (3:11) The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten
, but I'll open another issue for that.