Skip to content

Auto Generated +server.ts types for API calling #11101

@AlbertMarashi

Description

@AlbertMarashi

Something which kinda really sucks with creating APIs using SvelteKit +server.ts routes is that all the requests using fetch are untyped, as a result we don't receive typing on the front end, and have to manually constrain types

This can create a lot of surface area for bugs, as there can be a mismatch between the +server.ts and the fetch

My ideas are to somehow get SvelteKit to auto generate these types for use in the frontend

/api/hello/+server.ts

import { APIResponse, json } from "@svelte/kit"
export async function GET():  APIResponse<{ hello: "world" }>{
   return json({
      hello: "world" // these types are typechecked against the function response type to ensure correct data
   })
}

svelte code

export function json<T>(json: T): APIResponse<T> {
   // ...
}

/+page.ts

import { api_fetch } from "@svelte/kit" // a new tool exported by sveltekit that contains autogenerated types for all of the `+server.ts` routes
export async function load() {
   return {
        some_data: await api_fetch("GET", "/api/hello") // returns typed data
   }
   // the return type would look like { some_data: { hello: "world" } }
}

We could imagine that api_fetch looks like this using typescript function overloading with auto generated types

async function api_fetch(method: "GET", "/api/hello"): APIResponse<{ hello: "world" }>;
async function api_fetch(method: "GET", "/api/foo"): APIResponse<{ foo: "bar" }>;
async function api_fetch(method: Methods, url: string): APIResponse<any> {
   // ...
}

I think a lot of this should be possible with some typescript magic similar to how we're already doing with the load functions & page data

  1. How should parameterized routes work

Originally posted by @AlbertMarashi in #11042

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions