Skip to content

Typed fetch function, where the types are generated using the endpoints #5700

@pedeEli

Description

@pedeEli

Describe the problem

if you have the following endpoint

// src/routes/test.ts
import type { RequestHandler } from './__types/test'

export const GET: RequestHandler = async () => {
    return {
        body: {
            name: 'elias',
            age: 21
        }
    }
}

and you try to fetch the endpoint

// src/routes/page.svelte
fetch('/test')
    .then(data => data.json())
    .then(json => json.name)

the return object from data.json() should have the type

{
    name: string,
    age: number
}

Describe the proposed solution

like for the Load and the RequestHandler type, you could generate another file, which overrides the type for the fetch function

// .svelte-kit/types/fetch.d.ts
declare global {
    export function fetch(...): ...
}

and then reference this file in app.d.ts

// src/app.d.ts
/// <reference types="../.svelte-kit/types/fetch" />

And to know what the types are for the endpoint you could just export them in the endpoints and import then in the fetch.d.ts file

//src/routes/test.ts
import type { RequestHandler } from './__types/test'

export interface GETType {
    name: string,
    age: number
}

export const GET: RequestHandler<GETType> = async () => {
    return {
        body: {
            name: 'elias',
            age: 21
        }
    }
}

Alternatives considered

No response

Importance

would make my life easier

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions