My SvelteKit project is configured to authenticate with supabase. I followed this guide for the setup. Authentication and data fetching are working smoothly so far. However, I'm encountering a persistent Typescript error that I can't seem to resolve.
The data fetching occurs in this file:
// <!-- routes/playlists/+page.ts -->
import type { PageLoad } from './$types';
import { redirect } from '@sveltejs/kit';
export const load: PageLoad = async ({ parent }) => {
const { supabase, session } = await parent();
if (!session) {
throw redirect(303, '/');
}
const { data: playlist } = await supabase.from('playlist').select('*');
return {
user: session.user,
playlist
};
};
And here's the corresponding svelte file used to display the data:
<!-- routes/playlists/+page.svelte -->
<script lang="ts">
import type { PageData } from './$types';
import { json } from '@sveltejs/kit';
export let data: PageData;
</script>
<main>
<div>{data.user.email}</div> <!-- This works fine! -->
<ul>
{#each data.playlist as pl} <!-- Typescript complains about this -->
<li>
{pl.spotify_uri} <!-- and this -->
</li>
{/each}
</ul>
</main>
The errors I'm facing include:
'pl' is of type 'unknown'.
And
Argument of type '{ created_at: string; follower_count: number; last_auto_renewal: string; last_manual_renewal: string; playlist_id: number; spotify_uri: string; user_id: string | null; }[] |
null'
is not assignable to parameter of type 'ArrayLike<unknown>'.
Type 'null' is not assignable to type 'ArrayLike<unknown>'.
Despite these errors, the webpage displays everything as expected without any other issues. It appears that Typescript is just not satisfied. It's interesting to note that accessing data.user.email does not trigger any errors.
The autogenerated types from supabase schema look like this:
// $lib/supabase/schema.ts
export interface Database {
public: {
Tables: {
playlist: {
Row: {
created_at: string
follower_count: number
last_auto_renewal: string
last_manual_renewal: string
playlist_id: number
spotify_uri: string
user_id: string | null
}
...
Intellisense seems to infer these types correctly:Link to screenshot
This is my app.d.ts:
import { SupabaseClient, Session } from '@supabase/supabase-js';
import { Database } from '$lib/supabase/schema';
declare global {
namespace App {
interface Locals {
supabase: SupabaseClient<Database>;
getSession(): Promise<Session | null>;
}
interface PageData {
session: Session | null;
}
// interface Error {}
// interface Platform {}
}
}
I came across this discussion regarding a possible bug in Typescript: Link to GitHub issue. As a beginner in Typescript, I'm unsure if this is related to my situation or what exactly is causing the problem.
I was expecting SvelteKit/Typescript to automatically infer the types for "data.playlist" based on my schema within the #each loop, similar to how it's handled within the script tag. The fact that I'm encountering difficulties is puzzling. Thanks for taking the time to read through!