How to strongly type the response of SvelteKit endpoint in the component?

Viewed 694

So it looks like I have to separately type the response body going out of an endpoint and the props that I get from that body in the component. For example:

// index.ts (endpoint)

import type { RequestHandler } from "./__types";

export const get: RequestHandler<{
  foo: number;
  bar: string;
}> = () => {
  return {
    body: {
      foo: 42,
      bar: "hello"
    }
  };
};
// index.svelte (component)

<script lang="ts">
  export let foo;  // Not typed?
  export let bar;
</script>

I guess my question is why am I typing the response going out if I don't benefit from that typing in the component props?

1 Answers

This simply seems unsupported at the moment. The only thing that is generated are the params along the path (placeholders like [id] in file names).

Also, the source of truth would be the component, not the other way around, as all endpoints besides get can just return whatever they want.


I tried to work around this using type inference, but the generated component types do not appear to be accessible in TS files. If someone knows a workaround for that, it would be easy to type the endpoint correctly.

// src/lib/typing.ts
import type { SvelteComponentTyped } from 'svelte';

export type ComponentProps<T> = T extends SvelteComponentTyped<infer P> ? P : never;
import type { RequestHandler } from './__types';
import type Index from './index.svelte';
import type { ComponentProps } from '$lib/typing';

type Props = ComponentProps<Index>; // Unfortunately resolved to `any`

export const get: RequestHandler<Props> = async () => {
  //...
}

Inside a Svelte file:

<script lang="ts">
    import type { ComponentProps } from '$lib/typing';
    import type Index from './index.svelte';

    type Props = ComponentProps<Index>;
</script>

vs code screenshot of type resolution

Related