Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I strongly type a SvelteKit Request Handler?

I have a standalone sveltekit endpoint, and I'm not getting typescript typings for the endpoint.

// src/routes/login.ts
export async function post(request) {
  request.body; // shows as 'any' type

  return { status: 200, body: "ok" };
}

The request argument has an any type, and the function itself has a return type of Promise<any> which is not what I want.

I've found from types defined by sveltekit, but I'm not sure how to implement them.
import type {RequestHandler} from '@sveltejs/kit'

How can I tell typescript that the post() function is of type RequestHandler?

Also, I have a custom tsconfig.json file in the root of my project, but even when I delete this, I still don't get proper typings of my endpoint functions.

// tsconfig.json
{
    "extends": "./.svelte-kit/tsconfig.json",
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "$src/": ["src/"],
            "$src/*": ["src/*"]
        },
        "typeRoots": ["node_modules/@types", "src/types"]
    }
}

like image 954
TJBlackman Avatar asked Jun 17 '26 10:06

TJBlackman


1 Answers

I was searching for the same thing. I'll go with the following solution for now:

import type { RequestHandler } from '@sveltejs/kit';

export const post: RequestHandler = async ({ request }) => {
    request.body; // shows as 'ReadableStream<Uint8Array>' type

    return { status: 200, body: 'ok' };
};
like image 177
zeekrey Avatar answered Jun 20 '26 09:06

zeekrey